添加一些链接到一些单词问题


Add Some Links to some words issue

我有一些词,例如

"你好,这篇关于游戏的文章。我们的选择是火车游戏。游戏名称是我的小火车"

我想添加自动链接,如下所示

"游戏" » "http://www.mywebsite.com"

"火车游戏" » "http://www.myothersiteadrwesss.com"

"游戏" » "http://www.my3thsiteadress.com"

我用PHP和str_replace尝试过,但是在我的代码之后

"

游戏"一词嵌套了 2 个链接("http://www.mywebsite.com"和"http://www.my3thsiteadress.com")

"火车游戏"单词嵌套了 3 个链接(所有 3 个链接)

如何解决我的问题?

终于我想要了

<a href="http://www.my3thsiteadress.com">game</a>
<a href="http://www.myothersiteadrwesss.com">train games</a>
<a href="http://www.mywebsite.com">games</a>

字数可以更改

我认为你应该使用preg_replace而不是str_replace。这样,您可以指定要替换的更严格的正则表达式(有点像"匹配整个单词")。在这里,看看 http://php.net/manual/es/function.preg-replace.php)

最好的方法是多替换,一步一步......

<?php
    $string = "Hello this article about games. Our choice is train games. Name of game is My Little Train";
    // Replace first pass
    $string = str_replace("train games", "<a href='http://www.myothersiteadrwesss.com'>train ga3mes</a>", $string);
    $string = str_replace("games", "<a href='http://www.mywebsite.com'>ga3mes</a>", $string);
    $string = str_replace("game", "<a href='http://www.my3thsiteadress.com'>ga3me</a>", $string);
    $string = str_replace("ga3me", "game", $string);
    echo $string;
?>

输出

Hello this article about <a href="http://www.mywebsite.com">games</a>. Our choice
is <a href="http://www.myothersiteadrwesss.com">train games</a>. Name of <a
href="http://www.my3thsiteadress.com">game</a> is My Little Train

小提琴:http://phpfiddle.org/main/code/ny4-ium

注意

只要确保,你替换了一些非常大、复杂的东西,并且首先要记住所有的单词。接下来,你使用候选词。

使用str_replace,这是我能想到的最好的方法。否则,您需要使用regex并提供更复杂的搜索和替换。

我会将

键中的所有单词放在一个指向链接的数组中,如下所示:

$str = 'The original string that you want to replace games with!';
$arr = array('games' => 'http://website.com');

然后我会遍历该数组并使用str_replace替换字符串中的内容:

for($arr as $key => $val) {
   str_replace($key, $key . ' (' .  $val . ')', $str);
}

这将产生:

要替换游戏的原始字符串 (http://website.com)与!