Reputation: 131
I would like to create hyperlinks to the words in a paragraph.
For instance if the "Jim Carrey"
name is in the array matches the word in string, then the Jim Carrey name should be in Hyperlink of "www.domian.net/name(Jim Carrey)"
.
If the "mask"
word in the array matches the word in string then it should be replace with corresponding url like "www.domian.net/mask"
<?php
$string="Jim Carrey found the new Mask";
$array=array("Jim Carrey","mask");
echo preg_replace( '/\b('.implode( '|', $array ).')\b/i', '<a href=" ">$1</a>', $string );
?>
Upvotes: 1
Views: 602
Reputation: 324730
You seem to have the right idea about how to put a link around the chosen text, but you seem to have not even tried to put in an href
. Which is a shame, since it's as simple as typing in the URL with whatever parameter you want.
However, it does get a little complicated because you don't want the same thing both times (you want the literal word in one, but you want name(WORD)
in the other). You could try this:
$array = array("Jim Carrey"=>"name(Jim Carrey)","mask"=>"mask");
echo preg_replace_callback("/\b".implode("|",array_keys($array))."\b/i",
function($m) use ($array) {
return "<a href=\"http://domain.net/".$array[$m]."\">".$m."</a>";
},$string);
Upvotes: 1
Reputation: 2587
<?php
$string="Jim Carrey found the new Mask";
$arr=array("Jim Carrey","Mask");
foreach($arr as $val)
$string = str_replace($val, '<a href="http://domain.com/' . $val . '">' . $val . '</a>', $string);
echo $string;
?>
Upvotes: 0