PHP查找字符串中出现的所有子字符串
问题描述:
我需要解析一个HTML文档并查找其中所有出现的字符串asdf
。PHP查找字符串中出现的所有子字符串
我目前已将HTML加载到字符串变量中。我只是喜欢字符位置,所以我可以遍历列表来返回字符串后面的一些数据。
strpos
函数只返回第一个的发生。如何返回全部?
答
没有使用正则表达式,这样的事情应该返回字符串位置工作:
$html = "dddasdfdddasdffff";
$needle = "asdf";
$lastPos = 0;
$positions = array();
while (($lastPos = strpos($html, $needle, $lastPos))!== false) {
$positions[] = $lastPos;
$lastPos = $lastPos + strlen($needle);
}
// Displays 3 and 10
foreach ($positions as $value) {
echo $value ."<br />";
}
答
这可以使用strpos()函数来完成。以下代码是使用for循环实现的。这段代码非常简单而直截了当。
<?php
$str_test = "Hello World! welcome to php";
$count = 0;
$find = "o";
$positions = array();
for($i = 0; $i<strlen($str_test); $i++)
{
$pos = strpos($str_test, $find, $count);
if($pos == $count){
$positions[] = $pos;
}
$count++;
}
foreach ($positions as $value) {
echo '<br/>' . $value . "<br />";
}
?>
答
function getocurence($chaine,$rechercher)
{
$lastPos = 0;
$positions = array();
while (($lastPos = strpos($chaine, $rechercher, $lastPos))!== false)
{
$positions[] = $lastPos;
$lastPos = $lastPos + strlen($rechercher);
}
return $positions;
}
+0
与接受的答案非常相似,但我认为更容易阅读 –
答
可以反复调用strpos
功能,直到未找到匹配。您必须指定偏移量参数。
注意:在下面的示例中,搜索从下一个字符继续,而不是从上一次匹配结束。根据这个函数,aaaa
包含三个出现的子串aa
,不是两个。
function strpos_all($haystack, $needle) {
$offset = 0;
$allpos = array();
while (($pos = strpos($haystack, $needle, $offset)) !== FALSE) {
$offset = $pos + 1;
$allpos[] = $pos;
}
return $allpos;
}
print_r(strpos_all("aaa bbb aaa bbb aaa bbb", "aa"));
输出:
Array
(
[0] => 0
[1] => 1
[2] => 8
[3] => 9
[4] => 16
[5] => 17
)
看到的preg_match() – 2013-04-01 04:00:08