php字符串的所有子字符串,查询字符串中子字符串所有出现位置

js中 indexof()方法可返回某个指定的字符串值在字符串中首次出现的位置。运用第二个参数,循环调用就能获取到子串出现的所有位置

1 /**

2 * 查询字符串中子字符串出现位置

3 * @param str

4 * @param substr

5 * @return {array}

6 */

7 function search_substr_pos(str, substr) {

8 var _search_pos = str.indexof(substr), _arr_positions = [];

9 while (_search_pos > -1) {

10 _arr_positions.push(_search_pos);

11 _search_pos = str.indexof(substr, _search_pos + 1);

12 }

13 return _arr_positions;

14 }

15

16 var str = "look at me,is there anything can prove that i am a good guy ?";

17 var $_pos_substr = search_substr_pos(str, 'e');//子串位置

18 var $_times_substr = $_pos_substr.length;//出现次数

19

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

21 console.log($_times_substr); // 4

同理,php中使用strpos()

1 /**

2 * 查询字符串中子字符串出现位置

3 * @param $str

4 * @param $substr

5 * @return array

6 */

7 function search_substr_pos($str, $substr)

8 {

9 $_search_pos = strpos($str, $substr);

10 $_arr_positions = array();

11 while ($_search_pos > -1) {

12 $_arr_positions[] = $_search_pos;

13 $_search_pos = strpos($str, $substr, $_search_pos + 1);

14 }

15 return $_arr_positions;

16 }

17

18 $str = "look at me,is there anything can prove that i am a good guy ?";

19 $_pos_substr = search_substr_pos($str, 'e');//子串位置

20 $_times_substr = count($_pos_substr);//出现次数

21

22 print_r($_pos_substr); // array ( [0] => 9 [1] => 16 [2] => 18 [3] => 37 )

23 print_r($_times_substr); // 4

希望与广大网友互动??

点此进行留言吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值