Home >Backend Development >PHP Tutorial >PHP's preg_match_all() cannot match the specified string?
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
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;
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
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