Search string for a word and replace that word with different php links

Using PHP, how can I replace a word in a string with different links.

I want to replace the word web development with various links in order

This website development company is great. Good web development begins with ...

So

This web development is great. Good web development with ...

I tried using str_ireplace , but then both links lead to the same site.

Here is my code

 <?php $text = 'This web development company is great. A good web development starts with...'; $replaced = str_ireplace(array('web development', 'web development'),array('<a href="http://google.com">web development</a>', '<a href="http://yahoo.com">web development</a>'), $text); echo $replaced; 
+6
source share
4 answers

I think you can use the preg_replace() function as shown below:

 $pattern = '/(web development)(.*)(web development)/'; $replace = '<a href="http://google.com">web development</a>$2<a href="http://yahoo.com">web development</a>'; $result = preg_replace($pattern, $replace, $text); echo $result; 

Hope helps!

+5
source

Try with regex:

 <?php $text = 'This web development company is great. A good web development starts with...'; $regex = "/[^>]web development[^<]/i"; $replace = array(' <a href="http://google.com">web development</a> ', ' <a href="http://yahoo.com">web development</a> '); $count = 1; $replaced = preg_replace(array($regex,$regex), $replace, $text, $count); echo $replaced; 
+1
source

As in this section, you can do something like this (with preg_replace):

 $str = 'abc and abc'; $str = preg_replace('/abc/', 'google', $str, 1); $str = preg_replace('/abc/', 'yahoo', $str, 1); echo $str; 

It will display: "google and yahoo"

(I hope I understand your need)

0
source

I think you can do this with preg_replace .

Searches for the topic of matches with the pattern and replaces their replacement.

You can set the limit at a time when the word will be replaced.

limit: The maximum possible replacement for each template in each item is a string. The default is -1 (no limit).

So, I think that you can make a function that first, consider that "Web Development" has its own text, and then you do:

 $text = preg_replace("web development", "<a href='http://www.exemple.com'>web development</a>", $text, 1); 

x times

Remember the preg_replace function:

 preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] ) 

See the link in the PHP manual.

0
source

Source: https://habr.com/ru/post/951400/


All Articles