Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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">#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." 
like image 492
user1272589 Avatar asked Feb 26 '14 11:02

user1272589


People also ask

What is the difference between Str_replace and Preg_replace?

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.

What is use of Preg_replace in PHP?

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.

Can I use regex in replace?

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.

How do you replace words in regex?

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".


2 Answers

$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. 
like image 74
Nambi Avatar answered Oct 05 '22 21:10

Nambi


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()

like image 32
Ja͢ck Avatar answered Oct 05 '22 20:10

Ja͢ck