2

I've a array with regular expressions I use to replace URL's/hashtags with 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 a link, for ex: https://www.google.com/, it replaces correctly; if have a hashtag followed a text, for ex: #hello replace too, however, if have a link with a hashtag, for ex: https://www.google.com/#top the replacement is as follows:

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

and only the highlighted parts turn into links.

How to fix?

2
  • 1
    What's your expected output? Commented Jun 14, 2015 at 4:28
  • My expected output is like: https://www.google.com/#top but it only detect the #top (thus breaking the html) and no detect the completely link Commented Jun 14, 2015 at 4:30

1 Answer 1

1

It is because your second regex in array is also matching part after # in string.

Change your 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';

# now use in preg_replace
echo preg_replace($regs, $subs, $content);

It will 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>

Sign up to request clarification or add additional context in comments.

1 Comment

It is working now, but It is no longer detecting only hashtags like: #test

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.