【问题标题】:Preg match callback not working预匹配回调不起作用
【发布时间】:2017-03-14 23:10:21
【问题描述】:

我正在尝试编写一个函数来替换任何以 PID 开头和结尾的数字。我认为问题出在正则表达式中,但我无法弄清楚。代码如下。我也尝试了 (.) 而不是 (.*) - 没有区别。我知道我将不得不循环遍历匹配数组以获取所有匹配项,但我想首先让基本代码工作。有人能指出问题吗?

    function DoLinks($matches) {
     return ($matches[0]='<a href="someplace.com">Some place</a>');
    } 

    function Buildinks($text) {
      preg_replace_callback(
         "/PID(.*)PID/",
         "DoLinks",
         $text);
      return $text;
    }

    $text = "hello PID(199)PID";
    $text = Buildinks($text);
    echo $text;

【问题讨论】:

  • 你想用"hello &lt;a href="someplace.com"&gt;Some place&lt;/a&gt;"替换"hello PID(199)PID"吗?
  • 是的,没错。 LukStorms 发布的代码正是我想要做的。

标签: php regex preg-replace-callback


【解决方案1】:

函数 preg_replace_callback 返回一个值,您可以在 Buildinks 函数中返回该值。

$matches[0]= 可以在 DoLinks 中删除。

正则表达式现在有一个惰性匹配 .*?
以防万一您收到超过 1 个 PID 的文本。

<?php
function DoLinks($matches) {
    $pid = $matches[1];
    return '<a href="someplace.com">Some place with pid '.$pid.'</a>';
} 

function Buildinks($text) {
    return preg_replace_callback('/PID\((.*?)\)PID/', 'DoLinks', $text);
}

$text = "hello PID(199)PID and hello PID(200)PID";
$text = Buildinks($text);
echo $text;

【讨论】:

    猜你喜欢
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 2015-03-02
    • 2017-11-04
    • 2013-07-20
    相关资源
    最近更新 更多