【问题标题】:preg_match_all doesn't find anythingpreg_match_all 没有找到任何东西
【发布时间】:2026-02-02 11:15:01
【问题描述】:

我正在尝试将以下字符串 <a href="\"http://localhost/innovare-kh/wp-content/uploads/2014/07/CouncilTax.pdf\"">CouncilTax</a>preg_match_all() 匹配,但我一直收到 NULL。我已经测试过了on this website。这就是我使用该功能的方式:

preg_match_all('/(?<=href=\")(.*?\.(.*?))\\/', $description, $out)

description 是上面的字符串,$out 只是一个空变量。

谢谢, 内沃

【问题讨论】:

  • 启用error_reporting(E_ALL); 通知您的语法问题。
  • 输入的字符串是精确的字符串吗?
  • 字符串中的链接会有所不同,但其余部分相同。
  • @mario,它说没有找到结束分隔符.. 很奇怪。你看到我写的正则表达式有什么错误吗?
  • 反斜杠需要更多转义 \\\\ 来传递字符串并成为正则表达式中的文字字符。

标签: php regex preg-match-all


【解决方案1】:

你需要 3 个连续的反斜杠:

$description = '<a href="\"http://localhost/innovare-kh/wp-content/uploads/2014/07/CouncilTax.pdf\"">CouncilTax</a>';
preg_match_all('/(?<=href=\")(.*?\.(.*?))\\\/', $description, $out);
print_r($out);

输出:

Array
(
    [0] => Array
        (
            [0] => \"http://localhost/innovare-kh/wp-content/uploads/2014/07/CouncilTax.pdf\
        )

    [1] => Array
        (
            [0] => \"http://localhost/innovare-kh/wp-content/uploads/2014/07/CouncilTax.pdf
        )

    [2] => Array
        (
            [0] => pdf
        )

)

【讨论】: