PHP、JS怎样查询字符串中子字符串所有出现位置-php教程

资源魔 42 0
本篇文章次要讲述的是用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 js php开发教程 php开发资料 php开发自学

抱歉,评论功能暂时关闭!