为了账号安全,请及时绑定邮箱和手机立即绑定

preg_replace_callback 的单引号问题

preg_replace_callback 的单引号问题

PHP
MYYA 2021-11-26 16:49:08
我进行了广泛的搜索,但没有找到解决问题的提示或解决方案。问题是我无法用单引号匹配单词。也许这是由服务器、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??>结果:测试自动测试测试汽车的测试测试自动测试当我在我的网站上实施此代码时,汽车永远不会匹配。这就是为什么我认为它是由服务器,php或mysql设置引起的。我想知道我是否可以在我的正则表达式中解决这个问题。
查看完整描述

2 回答

?
holdtom

TA贡献1805条经验 获得超10个赞

终于找到了解决办法。单引号被存储在数据库中的&#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)

    { return ' <a href="https://example.com">'.$match[1].'</a> '; }, $message, 1);

echo $message;

?>

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


查看完整回答
反对 回复 2021-11-26
?
慕哥9229398

TA贡献1877条经验 获得超6个赞

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


$message = preg_replace_callback("~( auto(?:'s)? )~si", function ($match)

    { return ' <a href="https://example.com">'.$match[1].'</a> '; }, $message);

//                                                                   here __^^^


查看完整回答
反对 回复 2021-11-26
  • 2 回答
  • 0 关注
  • 176 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信