Using PHP replace regex with regex

I want to replace hash tags in a string with the same hash tag, but after adding a link to it

Example:

$text = "any word here related to #English must #be replaced."

I want to replace each hashtag with

#English ---> <a href="bla bla" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener">#English</a>
#be ---> <a href="bla bla" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener">#be</a>

So the output should be like that:

$text = "any word here related to <a href="bla bla" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener">#English</a> must <a href="bla bla" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener">#be</a> replaced."

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

$input_lines="any word here related to #English must #be replaced.";
preg_replace("/(#\w+)/", "<a href='bla bla'>$1</a>", $input_lines);

DEMO

OUTPUT:

any word here related to <a href='bla bla'>#English</a> must <a href='bla bla'>#be</a> replaced.

Solution 2

This should nudge you in the right direction:

echo preg_replace_callback('/#(\w+)/', function($match) {
    return sprintf('<a href="https://www.google.com?q=%s" rel="nofollow noreferrer noopener">%s</a>', 
        urlencode($match[1]), 
        htmlspecialchars($match[0])
    );
}, htmlspecialchars($text));

See also: preg_replace_callback()

Solution 3

If you need to refer to the whole match from the string replacement pattern all you need is a $0 placeholder, also called replacemenf backreference.

So, you want to wrap a match with some text and your regex is #\w+, then use

$text = "any word here related to #English must #be replaced.";
$text = preg_replace("/#\w+/", "<a href='bla bla'>$0</a>", $text);

Note you may combine $0 with $1, etc. In case you need to enclose a part of the match with some fixed strings you will have to use capturing groups. Say, you want to get access to both #English and English within one preg_replace call. Then use

preg_replace("/#(\w+)/", "<a href='path/$0'>$1</a>", $text)

Output will be any word here related to <a href='path/#English'>English</a> must <a href='path/#be'>be</a> replace.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply