php - Link being replaced not expected way when using preg_replace -


i've array regular expressions use replace url's/hashtags links using preg_replace:

$regs = array('!(\s|^)((https?://|www\.)+[a-z0-9_./?=;&#-]+)!i', '/#(\w+)/'); $subs = array(' <a href="$2" target="_blank">$2</a>', '<a href="/hashtag/$1" title="#$1">#$1</a>');  $output = preg_replace($regs, $subs, $content); 

if $content have link, ex: https://www.google.com/, replaces correctly; if have hashtag followed text, ex: #hello replace too, however, if have link hashtag, ex: https://www.google.com/#top replacement follows:

#top" target="_blank">https://www.google.com/#top ^^^^                                         ^^^^ 

and highlighted parts turn links.

how fix?

it because second regex in array matching part after # in string.

change regex to:

$regs = array('!(\s|^)((https?://|www\.)+[a-z0-9_./?=;&#-]+)!i', '/(?<=[\'"\s]|^)#(\w+)/'); $subs = array(' <a href="$2" target="_blank">$2</a>', '<a href="/hashtag/$1" title="#$1">#$1</a>'); $content = 'https://www.google.com/#top foobar #name';  # use in preg_replace echo preg_replace($regs, $subs, $content); 

it give you:

<a href="https://www.google.com/#top" target="_blank">https://www.google.com/#top</a> foobar <a href="/hashtag/name" title="#name">#name</a>


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -