2020年11月12日 星期四

PHP的非貪婪模式修飾符和‌‌preg_match_all()

前言

正規式搜尋在第一個符合時終止(Regular expression to stop at first match)

非貪婪模式 - (.*?)

PHP Pattern Modifiers的 U (PCRE_UNGREEDY)

https://www.php.net/manual/en/reference.pcre.pattern.modifiers.php  Pattern Modifiers

https://stackoverflow.com/a/37347478  PHP preg_match and preg_match_all functions

找HTML字串tag標籤里的內容:

<b>example: </b><div align=left>this is a test</div>

preg_match_all(
    "|<[^>]+>(.*)</[^>]+>|U",
    "<b>example: </b><div align=left>this is a test</div>",
    $matches
);
‌2 => 會有2個結果

‌‌$matches
‌array (
  0 => 
  array (
    0 => '<b>example: </b>',
    1 => '<div align=left>this is a test</div>',
  ),
  1 => 
  array (
    0 => 'example: ',
    1 => 'this is a test',
  ),
)
U - PHP的非貪婪模式修飾符

$matches[1] is an array of strings matched by the first parenthesized sub-pattern

$matches[1] 是第一個帶刮號括號(())的子模式匹配的陣列 => (.*)

正則用“|”是避免“/”的衝突,或是正則中跳脫“/”

preg_match_all(
    "/<[^>]+>(.*)<\/[^>]+>/U",
    "<b>example: </b><div align=left>this is a test!</div>",
    $matches
);

不使用非貪婪修飾符U

preg_match_all(
    "/<[^>]+>(.*?)<\/[^>]+>/",
    "<b>example: </b><div align=left>this is a test!</div>",
    $matches
);

其他

preg_match_all("/\{([\w\d_]+)\}/", "?new_year={year}&new_month={month}&new_day={day}", $matches)
‌3

‌‌$matches
‌array (
  0 => 
  array (
    0 => '{year}',
    1 => '{month}',
    2 => '{day}',
  ),
  1 => 
  array (
    0 => 'year',
    1 => 'month',
    2 => 'day',
  ),
)



沒有留言:

張貼留言