views:

71

answers:

4

I want to replace names in a text with a link to there profile.

$text = "text with names in it (John) and Jacob.";
$namesArray("John", "John Plummer", "Jacob", etc...);
$LinksArray("<a href='/john_plom'>%s</a>", "<a href='/john_plom'>%s</a>", "<a href='/jacob_d'>%s</a>", etc..);
//%s shout stay the the same as the input of the $text.

But if necessary a can change de array.

I now use 2 arrays in use str_replace. like this $text = str_replace($namesArray, $linksArray, $text); but the replace shout work for name with a "dot" or ")" or any thing like that on the end or beginning. How can i get the replace to work on text like this.

The output shout be "text with names in it (<a.....>John</a>) and <a ....>Jacob</a>."

+1  A: 

Try something like

$name = 'John';
$new_string = preg_replace('/[^ \t]?'.$name.'[^ \t]/', $link, $old_string);

PHP's preg_replace accepts mixed pattern and subject, in other words, you can provide an array of patterns like this and an array of replacements.

cypher
A: 

Look for regular expressions. Something like preg_replace().

preg_replace('/\((' . implode('|', $names)  . ')\)/', 'link_to_$1', $text);

Note that this solution takes the array of names, not just one name.

Mikulas Dite
i suck with regex
Remi
+1  A: 

Here is an example for a single name, you would need to repeat this for every element in your array:

$name = "Jacob";
$url = "<a href='/jacob/'>$1</a>";
$text = preg_replace("/\b(".preg_quote($name, "/").")\b/", $url, $text);
serg
thx, i still have a problem if i put this in loop the replace function search is the already replaced text, that could mass things up.
Remi
Can you provide an example?
serg
Try sorting an array by name length and start with the shortest.
serg
If you change the href to /Jacob/ in your example and have multiple Jacob's in the name array.
Remi
You mean same name different urls? Or just repeated records? If repeated records then you need to remove duplicates before replacing. If different urls for the same name then how to choose which name to replace with which url?
serg
+1  A: 

Done, and no regex:

$text = "text with names in it (John) and Jacob.";
$name_link = array("John" => "<a href='/john_plom'>", 
  "Jacob" => "<a href='/jacob'>"); 
foreach ($name_link as $name => $link) {
  $tmp = explode($name, $text);
  if (count($tmp) > 1) {
    $newtext = array($tmp[0], $link, $name, "</a>",$tmp[1]);
    $text = implode($newtext);
  }
}
echo $text;

The links will never change for each given input, so I'm not sure whether I understood your question. But I have tested this and it works for the given string. To extend it just add more entries to the $name_link array.

laconix