How to query all occurrences of substrings in a string using PHP and JS

little bottle
Release: 2023-04-06 09:34:02
forward
3435 people have browsed it

This article mainly talks about using PHP and js to query all occurrence positions of substrings in strings. It has certain reference value. Friends in need can refer to it.

The indexOf() method in JS can return the position where a specified string value first appears in the string. Using the second parameter, the loop call can get all the positions where the substring appears.

/**
   * 查询字符串中子字符串出现位置
   * @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
Copy after login

Related tutorials: JS video tutorial

##Similarly, use the strpos() method in PHP

/**
 * 查询字符串中子字符串出现位置
 * @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
Copy after login
Related tutorials:

PHP video tutorial

The above is the detailed content of How to query all occurrences of substrings in a string using PHP and JS. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!