Keval Domadia
Keval Domadia

Reputation: 4763

Regex for Hash tag but without a # in href

What I tried:

http://regexr.com?38d9s

#\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

Answers (2)

mertizci
mertizci

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

falsetru
falsetru

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

Related Questions