使用str_replace和preg_replace更改关键字

时间:2013-02-08 14:08:12

标签: php regex

我正在尝试在字符串中找到某些单词并将其替换为指向页面的链接

我有三个这样的数组(这只是一个例子而不是实际的事情:P)

$string = "Oranges apples pears Pears <p>oranges</p>";
$keyword = array('apples', 'pears', 'oranges');
$links = array('<a href="apples.php">Apples</a>', '<a href="pears.php">Pears</a>', '<a href="oranges.php">Oranges</a>');
$content = str_replace($keyword, $links, $string);
echo $content;

它取代了一些单词而不是全部单词,这是因为某些单词前面有空格,有些单词末尾有些空格,有些单词大写等等。

我想知道实现我想做的最好的方法是什么。我也试过preg_replace但我对正则表达式不太好。

2 个答案:

答案 0 :(得分:1)

只需使用str_ireplace

$string = "Oranges apples pears Pears <p>oranges</p>";
$keyword = array('apples', 'pears', 'oranges');
$links = array('<a href="apples.php">Apples</a>', '<a href="pears.php">Pears</a>', '<a href="oranges.php">Oranges</a>');
$content = str_ireplace($keyword, $links, $string);
echo $content;

空格应该没有问题。对于str_replace,如果搜索词之前/之后有空格,则不会。

如果您只想替换整个单词,则需要使用正则表达式:

$string = "Oranges apples pear Pears <p>oranges</p>";
$keyword = array('apples', 'pear', 'oranges'); // note: "pear" instead of "pears"
$links = array('<a href="apples.php">Apples</a>', '<a href="pears.php">Pears</a>', '<a href="oranges.php">Oranges</a>');
$content = preg_replace(array_map(function($element) {
    $element = preg_quote($element);
    return "/\b{$element}\b/i";
}, $keyword), $links, $string);
echo $content;

答案 1 :(得分:0)

您应该使用str_ireplace函数 - 它不是str_replace函数的区分大小写的变体