【问题标题】:Replace names in text with links用链接替换文本中的名称
【发布时间】:2011-03-06 12:51:46
【问题描述】:

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

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

但是如果需要的话可以改变de数组。

我现在使用 2 个数组在使用 str_replace。像这样$text = str_replace($namesArray, $linksArray, $text); 但是用“点”或“)”或任何类似的东西在结尾或开头替换名称。我怎样才能让替换来处理这样的文本。

输出喊叫是"text with names in it (&lt;a.....&gt;John&lt;/a&gt;) and &lt;a ....&gt;Jacob&lt;/a&gt;."

【问题讨论】:

  • 那么你想删除Jacob.中的一个点吗?
  • 你的$namesArray是什么样的?
  • 没有输出喊叫是“其中包含名称的文本 (John) 和 Jacob。”数组看起来像 $namesArray("John", "John Plummer", "Jacob", etc...);链接数组是 $LinksArray("%s", etc..); %s 喊保持与 $text 的输入相同。但如有必要,可以更改 de 数组。

标签: php arrays replace preg-replace


【解决方案1】:

完成,没有正则表达式:

$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 数组添加更多条目。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • thx,如果我把它放在循环中,我仍然有一个问题,替换功能搜索是已经替换的文本,这可能会使事情变得复杂。
    • 尝试按名称长度对数组进行排序并从最短的开始。
    • 如果您在示例中将 href 更改为 /Jacob/ 并且名称数组中有多个 Jacob。
    • 你的意思是同名不同的网址?还是只是重复记录?如果重复记录,那么您需要在替换之前删除重复项。如果同一个名字有不同的url,那么如何选择用哪个url替换哪个名字?
    【解决方案3】:

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

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

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

    【讨论】:

      【解决方案4】:

      试试类似的东西

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

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

      【讨论】:

        猜你喜欢
        • 2011-09-12
        • 2015-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-22
        • 2014-08-01
        • 1970-01-01
        • 2011-02-09
        相关资源
        最近更新 更多