2013-04-01 79 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 
) 
相關問題