教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 PHP、JS怎样查询字符串中子字符串所有出现位置

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

发布时间:2020-12-26   编辑:jiaochengji.com
教程集为您提供PHP、JS怎样查询字符串中子字符串所有出现位置等资源,欢迎您收藏本站,我们将为您提供最新的PHP、JS怎样查询字符串中子字符串所有出现位置资源
本篇文章主要讲述的是用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怎样查询字符串中子字符串所有出现位置的详细内容,更多请关注教程集其它相关文章!

  • 本文转载于:博客园,如有侵犯,请联系jquerycn@qq.com删除
  • 您可能感兴趣的文章:
    PHP、JS怎样查询字符串中子字符串所有出现位置
    PHP字符串函数与使用分析
    php字符串函数有哪些
    php5 字符串处理函数汇总
    mysql字符串截取函数SUBSTRING的用法
    php字符串查找 查找字符最后一次出现位置
    php字符串查找函数(strrpos与strchr)
    未结束的字符串常量怎么解决
    PHP中字符串处理的一些常用函数
    PHP字符串操作的一些函数

    [关闭]
    ~ ~