【问题标题】:How can I get all positions of a certain substring in a string?如何获取字符串中某个子字符串的所有位置?
【发布时间】:2016-03-06 02:30:12
【问题描述】:
我们有一个字符串:
$str = 'abc abc abc';
substr_count($str,'a') // gives 3
有什么办法可以得到一个数组,其中包含子串(本例中:a)出现的所有位置,例如:
[ 0 , 4 , 8 ]
【问题讨论】:
标签:
php
arrays
string
count
substring
【解决方案1】:
您可以使用preg_match_all() 并设置PREG_OFFSET_CAPTURE 标志,例如
<?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
)
【解决方案2】:
您可以使用此代码块来查找位置
<?php
$string = "abc abc abc";
$needle = "a";
$lastPos = 0;
$pos = array();
while(($lastPos = strpos($string, $needle, $lastPos))!== false) {
$pos[] = $lastPos;
$lastPos = $lastPos + strlen($needle);
}
foreach ($pos as $value) {
echo $value ."<br />";
}