简体   繁体   English

用于Hash标签的正则表达式,但href中没有#

[英]Regex for Hash tag but without a # in href

What I tried : 我试过了

http://regexr.com?38d9s http://regexr.com?38d9s

#\\w+ to match any Alpha-numeric starting with # #\\w+匹配任何以#开头的字母数字

and replacing it with: 并替换为:

<a href="/$&" />$&</a>

I want to get rid of # in href area of a tag and keep it as a link text, ie between starting and ending tags. 我想摆脱标签的href区域中的#,并将其保留为链接文本,即在开始和结束标签之间。 Check the example below. 检查以下示例。

What I want 我想要的是

if the sentence is: 如果句子是:

Lorem ipsum #set amet #dolor Lorem ipsum #set amet#美元

then, I want the output to be: 然后,我希望输出为:

Lorem ipsum <a href="/set">#set</a> amet <a href="/dolor">#dolor</a>

I am using preg_replace() without any delimiters. 我正在使用没有任何分隔符的preg_replace()

What I already have : 我已经拥有的:

preg_replace('/(?<=#)\\w+/', '<a href="/\\\\0" />\\\\0</a>', $comment)

it gives me: 它给了我:

Lorem ipsum #<a href="/set">set</a> amet #<a href="/dolor">dolor</a>

and NOT 并不是

Lorem ipsum <a href="/set">#set</a> amet <a href="/dolor">#dolor</a>

Notice the position of # 注意#的位置

Use capturing group. 使用捕获组。

Replace: 更换:

#(\w+)

with

<a href="/$1" />$&</a>

$1 is replaced with captured group 1 (word part) $1被捕获的组1替换(单词部分)


In PHP: 在PHP中:

$replaced = preg_replace('/#(\w+)/', '<a href="/\1" />\0</a>',
                         $sentence);

$replaced=preg_replace("/\\#([\\w\\d]+)/ui",'<a href="/\\1">\\0</a>',$text);

I suggest to you use this. 我建议您使用此。 On falsetru's answers he is using \\w. 在falsetru的答案上,他正在使用\\ w。 It means it will match only alphanumeric chars in English language. 这意味着它将仅匹配英语字母数字字符。 If you use \\w\\d it will match all utf-8 chars begining with #. 如果使用\\ w \\ d,它将匹配所有以#开头的utf-8字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM