How to prevent of re-replacing by second regex?(如何防止被第二个正则表达式重新替换?)
问题描述
我的输入有两个正则表达式,这些:
I have two regex(s) on the way of my input, these:
// replace a URL with a link which is like this pattern: [LinkName](LinkAddress)
$str= preg_replace("/[([^][]*)](([^()]*))/", "<a href='$2' target='_blank'>$1</a>", $str);
// replace a regular URL with a link
$str = preg_replace("/((?:(?:https?|ftp)://|www.)[-a-z0-9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|])/i","<a href="$1" target="_blank">untitled</a>", $str);
现在有一个问题(不知何故碰撞).对于常规 URL,一切都很好.但是对于基于模式的 URL,存在一个问题:第一个正则表达式创建该链接,第二个正则表达式再次创建其 href
属性值的链接.
Now there is a problem (somehow a collision). For regular URLs everything is fine. But for a pattern-based URLs, there is a problem: The first regex create a link of that and second regex again create a link of its href
-attribute value.
我该如何解决?
根据评论,我如何创建一个正则表达式而不是这两个正则表达式?(使用preg_replace_callback
).老实说,我试过了,但它不适用于任何类型的 URL ..
According to the comments, how can I create a single regex instead of those two regex? (using preg_replace_callback
). Honestly I tried it but it doesn't work for none kind of URLs ..
是否可以将它们结合起来?因为它们的输出并不相同.第一个有一个 LinkName,第二个有一个常量字符串 untitled
作为它的 LinkName.
Is combining them possible? Because the output of those isn't identical. The first one has a LinkName and the second one has a constant string untitled
as its LinkName.
推荐答案
$str = preg_replace_callback('/[([^][]*)](([^()]*))|((?:(?:https?|ftp)://|www.)[-a-z0-9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|])/i',
function($matches) {
if(isset($matches[3])) {
// replace a regular URL with a link
return "<a href='".$matches[3]."' target='_blank'>untitled</a>";
} else {
// replace a URL with a link which is like this pattern: [LinkName](LinkAddress)
return "<a href=".$matches[2]." target='_blank'>".$matches[1]."</a>";
}
}, $str);
echo $str;
一种方法是这样做.您将两个表达式与替代字符 |
合并在一起.然后在您的回调函数中,您只需检查是否设置了第三个捕获组 (isset($matches[3])
),如果是,则您的第二个正则表达式与字符串匹配并替换普通链接, 否则替换为链接/链接文本.
One way would be to do it like this. You merge your two expressions together with the alternative character |
. Then in your callback function you just check if your third capture group is set (isset($matches[3])
) and if yes, then your second regular expression matched the string and you replace a normal link, otherwise you replace with link/linktext.
我希望你明白一切,我可以帮助你.
I hope you understand everything and I could help you.
这篇关于如何防止被第二个正则表达式重新替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何防止被第二个正则表达式重新替换?
基础教程推荐
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 使用 PDO 转义列名 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01