首頁  >  文章  >  後端開發  >  PHP、JS怎麼查詢字串中子字串所有出現位置

PHP、JS怎麼查詢字串中子字串所有出現位置

little bottle
little bottle轉載
2019-04-23 14:30:423437瀏覽

本篇文章主要講述的是用PHP以及js查詢字串中子字串所有出現位置,具有一定的參考價值,有需要的朋友可以參考一下。

JS中indexOf()方法可傳回某個指定的字串值在字串中首次出現的位置。運用第二個參數,循環呼叫就能取得到子字串出現的所有位置。

/**
   * 查询字符串中子字符串出现位置
   * @param str
   * @param substr
   * @return {Array}
   */
  function search_substr_pos(str, substr) {
    var _search_pos = str.indexOf(substr), _arr_positions = [];
    while (_search_pos > -1) {
      _arr_positions.push(_search_pos);
      _search_pos = str.indexOf(substr, _search_pos + 1);
    }
    return _arr_positions;
  }

  var str = "look at me,is there anything can prove that I am a good guy ?";
  var $_pos_substr = search_substr_pos(str, 'e');//子串位置
  var $_times_substr = $_pos_substr.length;//出现次数

  console.log($_pos_substr);    //  [ 9, 16, 18, 37 ]
  console.log($_times_substr);  //  4

相關教學:JS影片教學

#同理,PHP使用strpos()方法

/**
 * 查询字符串中子字符串出现位置
 * @param $str
 * @param $substr
 * @return array
 */
function search_substr_pos($str, $substr)
{
  $_search_pos = strpos($str, $substr);
  $_arr_positions = array();
  while ($_search_pos > -1) {
    $_arr_positions[] = $_search_pos;
    $_search_pos = strpos($str, $substr, $_search_pos + 1);
  }
  return $_arr_positions;
}

$str = "look at me,is there anything can prove that I am a good guy ?";
$_pos_substr = search_substr_pos($str, 'e');//子串位置
$_times_substr = count($_pos_substr);//出现次数

print_r($_pos_substr);    //  Array ( [0] => 9 [1] => 16 [2] => 18 [3] => 37 )
print_r($_times_substr);  //  4

相關教學:PHP影片教學

#

以上是PHP、JS怎麼查詢字串中子字串所有出現位置的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:cnblogs.com。如有侵權,請聯絡admin@php.cn刪除