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">#English</a> #be ---> <a href="bla bla">#be</a>
So the output should be like that:
$text = "any word here related to <a href="bla bla">#English</a> must <a href="bla bla">#be</a> replaced."
str_replace replaces a specific occurrence of a string, for instance "foo" will only match and replace that: "foo". preg_replace will do regular expression matching, for instance "/f. {2}/" will match and replace "foo", but also "fey", "fir", "fox", "f12", etc.
PHP | preg_replace() Function The preg_replace() function is an inbuilt function in PHP which is used to perform a regular expression for search and replace the content.
How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.
Find/Replace with Regular Expression (Regex) or Wildcards. Word supports find/replace with it own variation of regular expressions (regex), which is called wildcards. To use regex: Ctrl-H (Find/Replace) ⇒ Check "Use wildcards" option under "More".
$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.
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">%s</a>', urlencode($match[1]), htmlspecialchars($match[0]) ); }, htmlspecialchars($text));
See also: preg_replace_callback()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With