如何获取字符串中某个子字符串的所有位置? [英] How can I get all positions of a certain substring in a string?
本文介绍了如何获取字符串中某个子字符串的所有位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们有一个字符串:
$str = 'abc abc abc';
substr_count($str,'a') // gives 3
有没有什么办法可以得到一个包含子字符串(在这个例子中:a
)出现的所有位置的数组,例如:
Is there any way to get an array containing all positions where the substring(In this example: a
) occurs, for example:
[ 0 , 4 , 8 ]
推荐答案
您可以使用 preg_match_all()
并设置 PREG_OFFSET_CAPTURE
标志,例如
You can use preg_match_all()
and set the PREG_OFFSET_CAPTURE
flag, e.g.
<?php
$str = 'abc abc abc';
preg_match_all("/a/", $str, $m, PREG_OFFSET_CAPTURE);
print_r(array_column($m[0], 1));
?>
输出:
Array
(
[0] => 0
[1] => 4
[2] => 8
)
这篇关于如何获取字符串中某个子字符串的所有位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文