簡體   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