繁体   English   中英

用链接替换文本中的名称

[英]Replace names in text with links

我想用指向该个人资料的链接替换文本中的名称。

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

但如有必要,可以更改数组。

我现在在使用str_replace中使用2个数组。 像这样$text = str_replace($namesArray, $linksArray, $text); 但是替换喊话可以在名称的末尾加上“。”或“)”或类似名称。 我如何才能将替换内容用于此类文本。

输出的喊叫是"text with names in it (<a.....>John</a>) and <a ....>Jacob</a>."

尝试类似

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

PHP的preg_replace接受混合模式和主题,换句话说,您可以提供这样的模式数组和替换数组。

这是单个名称的示例,您需要对数组中的每个元素重复此操作:

$name = "Jacob";
$url = "<a href='/jacob/'>$1</a>";
$text = preg_replace("/\b(".preg_quote($name, "/").")\b/", $url, $text);

完成,没有正则表达式:

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

对于每个给定的输入,链接永远不会改变,所以我不确定是否理解您的问题。 但是我已经测试过了,它适用于给定的字符串。 要扩展它,只需在$name_link数组中添加更多条目即可。

寻找正则表达式。 类似于preg_replace()

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

请注意,此解决方案采用名称数组,而不只是一个名称。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM