Php 用链接替换文本中的名称

Php 用链接替换文本中的名称,php,arrays,replace,preg-replace,Php,Arrays,Replace,Preg Replace,我想将文本中的名称替换为指向该配置文件的链接 $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'&g

我想将文本中的名称替换为指向该配置文件的链接

$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.
$text=“包含姓名的文本(John)和Jacob。”;
$namesArray(“John”、“John Plummer”、“Jacob”等);
$LinksArray(“,”,“,”等);
//%s shout与$text的输入保持一致。
但如有必要,可以更改de数组

我现在使用str_replace中的两个数组。像这样,
$text=str\u replace($namesArray,$linksArray,$text)
但是,在名称的结尾或开头加上“点”或“)”或任何类似的东西都可以。我怎样才能让replace处理这样的文本呢

输出应该是
“包含姓名的文本(John)和Jacob。”

试试类似的方法

$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);
$name=“Jacob”;
$url=”“;
$text=preg\u replace(“/\b”(.preg\u 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;
$text=“包含姓名的文本(John)和Jacob。”;
$name_link=array(“John”=>”,$tmp[1]);
$text=内爆($newtext);
}
}
echo$文本;

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

那么您是否希望在
Jacob中删除一个点。
?您的
$namesArray
看起来像什么?否输出为“包含名称的文本”(,等等);%s shout与$text的输入保持一致。但是如果有必要,a可以更改de array.thx,如果我将其放入循环中,我仍然有一个问题替换函数搜索是已经替换的文本,这可能会造成大量问题。请尝试按名称长度对数组进行排序,并从最短的开始。如果您在示例中将href更改为/Jacob/,并且名称数组中有多个Jacob。您的意思是相同的名称不同的URL?还是只是重复记录?如果记录重复,则需要在替换之前删除重复记录。如果相同的名称有不同的url,那么如何选择用哪个url替换哪个名称?
$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;