【问题标题】:Preg_replace finds a match where there shouldn't be onePreg_replace 找到一个不应该存在的匹配项
【发布时间】:2023-02-24 01:56:36
【问题描述】:

所以我正在做我自己的简单 Markdown 格式化程序。当我的代码块格式化程序遇到问题时,我正在修复最后一个问题。由于某种原因,它匹配了一个不应该匹配的额外时间。


$matches = [
    "```\ncode block \n```",
    "code block \n"
];

private function code_block_format($matches): string
    {
        // get a line
        $regex = '/([^\n]*)\n?/';
        // wrap that line into <code> elem + new line
        $repl = '<code>$1</code>' . "\n";
        // remove trailing linebreaks + spaces
        $matches[1] = trim($matches[1]);
        $ret = preg_replace($regex, $repl, $matches[1]); // this returns the badly formatted string
        $ret = "<pre>\n" . $ret . "</pre>";
        return $ret;
    }

preg_replace 只返回 &lt;code&gt;code block&lt;/code&gt;\n 但出于某种原因我得到了一个额外的元素 &lt;code&gt;code block&lt;/code&gt;\n&lt;code&gt;&lt;/code&gt;\n

关于世界上什么可能导致它锁定到那里某处的“”字符串的任何帮助?

【问题讨论】:

    标签: php regex


    【解决方案1】:

    你可以试试这个,因为你的首字母是零个或多个匹配项,并且可以创建一个只有换行符的组......

    $regex = '/([^
    ]+)
    ?/';
    

    它应该输出:

    <pre>
    <code>code block</code>
    </pre>
    

    【讨论】:

      【解决方案2】:

      $regex = '/([^ ]*) ?/'; 返回不包含 的字符串零次或多次,所以基本上是所有内容。

      *更改为+,表示出现一次或多次。

      $regex = '/([^ ]+) ?/';

      我实际上无法弄清楚为什么 * 返回第二组。 /[^a]*/g 为不包含 a 的任何文本返回两个组,我希望有一个。

      虽然,您的代码似乎不必要地复杂。您是否只是想用 trim() 从 $match[1] 中删除空格,然后用 &lt;code&gt;&lt;/code&gt; 包围它?

      您可以将标签连接到修剪后的 $matches[1] 上:

      return '&lt;code&gt;' . $matches[1] . '&lt;/code';

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多