我需要解析HTML文档并查找其中出现的所有字符串asdf.
我目前将HTML加载到字符串变量中.我只想要字符位置,所以我可以遍历列表以返回字符串后的一些数据.
该strpos函数仅返回第一个匹配项.如何归还所有这些?
Ada*_*her 76
不使用正则表达式,这样的东西应该用于返回字符串位置:
$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 />";
}
Run Code Online (Sandbox Code Playgroud)
Sal*_*n A 16
您可以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"));
Run Code Online (Sandbox Code Playgroud)
输出:
Array
(
[0] => 0
[1] => 1
[2] => 8
[3] => 9
[4] => 16
[5] => 17
)
Run Code Online (Sandbox Code Playgroud)
function getocurence($chaine,$rechercher)
{
$lastPos = 0;
$positions = array();
while (($lastPos = strpos($chaine, $rechercher, $lastPos))!== false)
{
$positions[] = $lastPos;
$lastPos = $lastPos + strlen($rechercher);
}
return $positions;
}
Run Code Online (Sandbox Code Playgroud)