首頁  >  文章  >  後端開發  >  php的preg_match_all()符合不到指定的字串求解?

php的preg_match_all()符合不到指定的字串求解?

WBOY
WBOY原創
2016-09-29 09:33:001540瀏覽

demo:

<code>$html='<div class="p-img"><a href="url"></a></div><div class="p-img"><img src="xx"></div>';

preg_match_all('/<div class="p-img">(.*?)<\/div>/', $html, $out);

var_dump($out);
</code>

目標字串$html,希望匹配

,發現最後輸出的$out是一直是empty,如何才能正確的匹配所有的結果,求正則高手指點

找到答案之後的補充說明:

利用爬蟲從網路上取得到的dom結構,裡面有很多的空格和換行,如果想把目標html配對出來,正規表示式後面需要加入模式修正符號

<code>preg_match_all('/<div class="p-img">(.*?)<\/div>/is', $html, $out);</code>

/i 忽略大小寫

/s 將字串視為單行,換行符作為普通字元;

回覆內容:

demo:

<code>$html='<div class="p-img"><a href="url"></a></div><div class="p-img"><img src="xx"></div>';

preg_match_all('/<div class="p-img">(.*?)<\/div>/', $html, $out);

var_dump($out);
</code>

目標字串$html,希望匹配

,發現最後輸出的$out是一直是empty,如何才能正確的匹配所有的結果,求正則高手指點

找到答案之後的補充說明:

利用爬蟲從網路上取得到的dom結構,裡面有很多的空格和換行,如果想把目標html配對出來,正規表示式後面需要加入模式修正符號

<code>preg_match_all('/<div class="p-img">(.*?)<\/div>/is', $html, $out);</code>

/i 忽略大小寫

/s 將字串視為單行,換行符作為普通字元;

<code>$html='<div class="p-img"><a href=\'url\'></div><div class="p-img"><img src=\'xx\'></div>';

preg_match_all('/<div\sclass="p\-img">(.*?)<\/div>/is', $html, $out);

var_dump($out);</code>

輸出:

<code>array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(39) "<div class="p-img"><a href='url'></div>"
    [1]=>
    string(39) "<div class="p-img"><img src='xx'></div>"
  }
  [1]=>
  array(2) {
    [0]=>
    string(14) "<a href='url'>"
    [1]=>
    string(14) "<img src='xx'>"
  }
}</code>

要我怎麼說呢,你的 $html 裡面的 / 應該 /,並且 ' 沒有轉義為 '

我運行通不過,你知道麼,是你文法問題,還是正則的問題?

答案在$html定義哪裡。

-號需要轉義

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn