PHP|How to Fix the preg_match_all Error "Unknown modifier"

Sometimes the following warning appears when running PHP code:
Warning: preg_match_all() [function.preg-match-all]: Unknown modifier 'a' in C:\php\nobuneko\test.php on line 24
This means that the preg_match_all function encountered an unknown modifier. Since modifiers appear immediately after the closing slash of a regular expression, the first step is to inspect the slashes (/) used in the pattern.

Incorrect Example

$html_source <<<CAT
<a href="noraneko.html">野良猫A</a><br />
飼い猫A<br />
飼い猫B<br />
<a href="noraneko2.html">野良猫B</a><br />
<a href="noraneko3.html">野良猫C</a><br />
<a href="noraneko4.html">野良猫D</a><br />
CAT;

$num = preg_match_all("/<a href=\"[^<]+\">.+?</a>/", $html_source, $array_match);
echo $num;
echo "<br>\n";
print_r($array_match);

Cause: Unescaped Slash Inside the Pattern

The pattern contains </a>, and the slash (/) is interpreted as the end of the regular expression. Escaping the slash fixes the issue.

Incorrect:
$num = preg_match_all("/<a href=\"[^<]+\">.+?</a>/", $html_source, $array_match);

Correct:
$num = preg_match_all("/<a href=\"[^<]+\">.+?<\/a>/", $html_source, $array_match);

preg_match_all Syntax

preg_match_all(pattern, subject, matches)
・pattern -- Regular expression pattern
・subject -- The string to search
・matches -- Array storing matched results
Return value: number of matches.

Correct Example: Extracting Links from HTML

$html_source <<<CAT
<a href="noraneko.html">野良猫A</a><br />
飼い猫A<br />
飼い猫B<br />
<a href="noraneko2.html">野良猫B</a><br />
<a href="noraneko3.html">野良猫C</a><br />
<a href="noraneko4.html">野良猫D</a><br />
CAT;

$num = preg_match_all("/<a href=\"[^<]+\">.+?<\/a>/", $html_source, $array_match);
echo $num;
echo "<br>\n";
print_r($array_match);

Output

4<br>
Array
(
[0] => Array
(
[0] => <a href="noraneko.html">野良猫A</a>
[1] => <a href="noraneko2.html">野良猫B</a>
[2] => <a href="noraneko3.html">野良猫C</a>
[3] => <a href="noraneko4.html">野良猫D</a>
)
)

前へ

PHP|preg_match_all のエラー「Unknown modifier」の原因と正しい対処方法

次へ

PHPエラー「Fatal error: Call to undefined function mb_convert_encoding()」の原因と解決方法(Windows用PHP)