preg_replace_callback 的单引号问题

我进行了广泛的搜索,但没有找到解决问题的提示或解决方案。问题是我无法用单引号匹配单词。也许这是由服务器、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. 测试汽车的测试

  3. 测试自动测试

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


MYYA
浏览 177回答 2
2回答

holdtom

终于找到了解决办法。单引号被存储在数据库中的&#39; 更换~( auto(?:'s)? )~与~( auto(?:&#39;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)&nbsp; &nbsp; { return ' <a href="https://example.com">'.$match[1].'</a> '; }, $message, 1);echo $message;?>暗示。提示。所以在类似的情况下,检查一个字符是如何存储在你的数据库中的,并在你的正则表达式中使用它。

慕哥9229398

只需删除1preg_replace 末尾的(这意味着只替换一次):$message = preg_replace_callback("~( auto(?:'s)? )~si", function ($match)&nbsp; &nbsp; { return ' <a href="https://example.com">'.$match[1].'</a> '; }, $message);//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;here __^^^
打开App,查看更多内容
随时随地看视频慕课网APP