将主题标签转换为超链接,无需部分匹配 htmlentities
我想将所有出现的 #word
替换为 HTML 链接。我为此编写了一个 preg_replace()
调用:
$text = preg_replace('~#([\p{L}|\p{N}]+)~u', '<a href="/?aranan=$1">#$1</a>', $text);
问题是,这个正则表达式还匹配 '
等 html 字符代码,因此会损坏输出。
我需要排除 &#
前面的字母数字子字符串,但我不知道如何使用正则表达式来做到这一点。
I want to replace all occurrences of #word
with an HTML link. I have written a preg_replace()
call for this:
$text = preg_replace('~#([\p{L}|\p{N}]+)~u', '<a href="/?aranan=$1">#$1</a>', $text);
The problem is, this regular expression also matches the html character codes like '
and therefore corrupts the output.
I need to exclude alphanumeric substrings which are preveded by , but I do not know how to do that using regular expressions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个负面的后向断言: http://www.php.net/ Manual/en/regexp.reference.assertions.php
仅当前面没有 & 时才匹配 #
That's a negative lookbehind assertion: http://www.php.net/manual/en/regexp.reference.assertions.php
Matches # only if not preceded by &
http://gskinner.com/RegExr/
使用此在线正则表达式构造函数。他们对您可能想要使用的每个标志都有解释......并且您将在示例文本中看到突出显示的匹配项。
是的,使用 [a-zA-Z]
http://gskinner.com/RegExr/
use this online regular expression constructor. They have explanation for every flag you may want to use.. and you will see highlighted matches in example text.
and yes use [a-zA-Z]
元素,请正确对
href
值进行 URL 编码,并对打印的链接文本进行 HTML 编码。代码:(演示)
未渲染的输出:
渲染的 HTML:
<a>
elements, then properly URL-encode thehref
value and HTML-encode the printed link text.Code: (Demo)
Unrendered output:
Rendered HTML:
您需要在正则表达式语句中添加
[A-Za-z]
规则,以便它仅将自身限制为字母而不是数字。稍后我将用一个示例进行编辑。You would need to add a
[A-Za-z]
rule in your regular expression statement so that it only limits itself to letters and no numbers.I will edit with an example later on.