Reputation: 4763
What I tried:
#\w+
to match any Alpha-numeric starting with #
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, i.e. between starting and ending tags. Check the example below.
What I want
if the sentence is:
Lorem ipsum #set amet #dolor
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.
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 #
Upvotes: 1
Views: 367
Reputation: 528
$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. 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 #.
Upvotes: 0
Reputation: 368954
Use capturing group.
Replace:
#(\w+)
with
<a href="/$1" />$&</a>
$1
is replaced with captured group 1 (word part)
In PHP:
$replaced = preg_replace('/#(\w+)/', '<a href="/\1" />\0</a>',
$sentence);
Upvotes: 2