Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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

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

This web development company is great. A good web development starts with...

like so

This web development company is great. A good web development starts with...

i have 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;
like image 276
Ronny K Avatar asked Aug 09 '13 15:08

Ronny K


1 Answers

I think you can use the preg_replace() function, as the following:

$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!

like image 197
Hanfeng Avatar answered Oct 18 '22 20:10

Hanfeng