【问题标题】:single quote problem with preg_replace_callbackpreg_replace_callback 的单引号问题
【发布时间】:2019-08-17 08:40:46
【问题描述】:

我进行了广泛的搜索,但没有找到针对我的问题的提示或解决方案。 问题是我无法用单引号匹配单词。这可能是由服务器、php 或 mysql 设置引起的。 我想知道我是否可以解决这个问题。

我在这里有一个活生生的例子:Fiddle with preg_replace_callback

<?php
$message = "1. test autotest test<br \>2. test auto's test<br \>3.test auto test ";
$message = preg_replace_callback("~( auto(?:'s)? )~si", function ($match)
    { return ' <a href="https://example.com">'.$match[1].'</a> '; }, $message, 1);
echo $message;
// here number 2 is correctly replaced, on my site number 3. Number 2 is not working on my site. I suspect the single quote is the problem on my site. Is there a workaround?
?>

结果:

  1. 测试自动测试测试
  2. 测试 auto's 测试
  3. 测试自动测试

当我在我的网站上实现此代码时,auto's 永远不会匹配。这就是为什么我认为它是由服务器、php 或 mysql 设置引起的。我想知道我是否可以在我的正则表达式中解决这个问题。

【问题讨论】:

    标签: php regex pcre preg-replace-callback single-quotes


    【解决方案1】:

    只需删除 preg_replace 末尾的1 (这意味着只替换一次):

    $message = preg_replace_callback("~( auto(?:'s)? )~si", function ($match)
        { return ' <a href="https://example.com">'.$match[1].'</a> '; }, $message);
    //                                                                   here __^^^
    

    【讨论】:

    • 不,这不是问题所在。消息 1 只是确保只处理第一个匹配项。示例中的第一个匹配项是 auto,在我的站点上无法识别 auto,因此第一个匹配项是 auto。只是为了确保我在没有 ,1 的情况下进行了测试,但这没有区别。
    【解决方案2】:

    终于找到了解决办法。 单引号在数据库中存储为&amp;#39;~( auto(?:&amp;#39;s)? )~ 替换~( auto(?:'s)? )~ 解决了我的问题。

    完整的工作代码:

    <?php
    $message = "1. test autotest test<br \>2. test auto's test<br \>3.test auto test ";
    $message = preg_replace_callback("~( auto(?:&#39;s)? )~si", function ($match)
        { return ' <a href="https://example.com">'.$match[1].'</a> '; }, $message, 1);
    echo $message;
    ?>
    

    提示。小费。所以在类似的情况下,检查一个字符是如何存储在你的数据库中的,并在你的正则表达式中使用它。

    【讨论】:

      猜你喜欢
      • 2013-01-02
      • 1970-01-01
      • 2016-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-10
      • 2011-01-03
      • 1970-01-01
      相关资源
      最近更新 更多