Home  >  Article  >  Backend Development  >  PHP's preg_match_all() cannot match the specified string?

PHP's preg_match_all() cannot match the specified string?

WBOY
WBOYOriginal
2016-09-29 09:33:001541browse

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>

The target string $html, I hope to match

, but I found that the last output $out is always empty. How can I match all the results correctly? Please give me some guidance from a regular expert


Additional explanation after finding the answer:

Use the crawler to obtain the DOM structure from the Internet. There are many spaces and line breaks in it. If you want to match the target HTML, you need to add a pattern correction symbol after the regular expression

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

/i ignore case

/s treats the string as a single line and newlines as normal characters;

Reply content:

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>

The target string $html, I hope to match

, but I found that the last output $out is always empty. How can I match all the results correctly? Please give me some guidance from a regular expert


Additional explanation after finding the answer:

Use the crawler to obtain the DOM structure from the Internet. There are many spaces and line breaks in it. If you want to match the target HTML, you need to add a pattern correction symbol after the regular expression

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

/i ignore case

/s treats the string as a single line and newlines as normal characters;

<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>

Output:

<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>

What should I say? The / in your $html should be /, and ' is not escaped to '

I can’t run it. Do you know if it’s a problem with your grammar or regularity?

The answer is where $html is defined.

-number needs to be escaped

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn