多个正则表达式干扰
我使用正则表达式以纯文本形式创建 html 标签。像这样
循环
$SearchArray[] = "/\b(".preg_quote($user['name'], "/").")\b/i";
$ReplaceArray[] = '<a href="'.$user['url'].'">$1</a>';
-
$str = preg_replace($SearchArray, $ReplaceArray, $str);
我正在寻找一种不匹配标签中的$user['name']
的方法。
I use regex to create html tags in plain text. like this
loop
$SearchArray[] = "/\b(".preg_quote($user['name'], "/").")\b/i";
$ReplaceArray[] = '<a href="'.$user['url'].'">$1</a>';
-
$str = preg_replace($SearchArray, $ReplaceArray, $str);
I'm looking for a way to not match $user['name']
in a tag.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
preg_replace_callback()
< /a>对于 5.3+:
对于 5.2+:
You could use
preg_replace_callback()
for 5.3+:
for 5.2+:
所以问题是,您要对文档进行多次传递,在每次传递中替换不同的用户名,并且您担心会无意中替换在上一次传递中创建的标签内的名称,对吧?
我会尝试在一次传递中完成所有替换,使用
preg_replace_callback
作为@ircmaxwell建议,以及一个可以匹配任何合法用户的正则表达式姓名。在回调函数中,您查找匹配的字符串以查看它是否是真实的用户名。如果是,则返回生成的链接;如果没有,则返回匹配的字符串以重新插入。So the problem is that you're making several passes over the document, replacing a different user name in each pass, and you're afraid you'll unintentionally replace a name inside a tag that was created in a previous pass, right?
I would try to do all of the replacements in one pass, using
preg_replace_callback
as @ircmaxwell suggested, and one regex that can match any legal user name. In the callback function, you look up the matched string to see if it's a real user's name. If it is, return the generated link; if not, return the matched string for reinsertion.看起来您正在尝试向文档添加一堆锚点。您是否考虑过使用 SimpleXML。这假设锚标记是较大 xhtml 文档的一部分。
simpleXML 在这些情况下对我有很大帮助。即使这并不完全是您想要做的,它也会比正则表达式快得多。
It looks like you're trying to add a bunch of anchors to a document. Have you thought of using SimpleXML. This assumes that the anchor tags are part of a larger xhtml document.
simpleXML helps me a lot in these situations. It'll be a lot faster than regex, even if this isn't exactly what you want to do.