2013-04-01 184 views
35

我需要解析一个HTML文档并查找其中所有出现的字符串asdfPHP查找字符串中出现的所有子字符串

我目前已将HTML加载到字符串变量中。我只是喜欢字符位置,所以我可以遍历列表来返回字符串后面的一些数据。

strpos函数只返回第一个的发生。如何返回全部

+2

看到的preg_match() – 2013-04-01 04:00:08

回答

57

没有使用正则表达式,这样的事情应该返回字符串位置工作:

$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 />"; 
} 
+8

请使用任务'if'语句要小心。在这种情况下,'while'循环不适用于位置'0'。我已经更新了你的答案。 – Robbert

+0

卓越的修复,但对于那些需要查找特殊字符(é,ë,...)的用mb_strpos替换strpos,否则它将不起作用 – Brentg

3

使用preg_match_all找到所有出现。

preg_match_all('/(\$[a-z]+)/i', $str, $matches); 

有关进一步的参考检查this link

+6

他正在寻找字符串位置,而不仅仅是匹配。他也希望匹配“asdf”,而不是[az] ... –

+4

不要提,那个'preg_'函数是相当慢的... – trejder

9

它更好使用substr_count。查看php.net

+5

这只给你计数,而不是他们的位置,因为问题要求 – DaveB

+0

“这个函数不计算重叠的子串“。对于字符串'abababa',当你看'aba'时,它只会计数2次而不是3 –

1

这可以使用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 />"; 
} 

?> 
6
function getocurence($chaine,$rechercher) 
     { 
      $lastPos = 0; 
      $positions = array(); 
      while (($lastPos = strpos($chaine, $rechercher, $lastPos))!== false) 
      { 
       $positions[] = $lastPos; 
       $lastPos = $lastPos + strlen($rechercher); 
      } 
      return $positions; 
     } 
+0

与接受的答案非常相似,但我认为更容易阅读 –

11

可以反复调用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 
) 
相关问题