【问题标题】:Keyword Replacement using str_replace and preg_replace使用 str_replace 和 preg_replace 进行关键字替换
【发布时间】:2013-02-08 14:08:11
【问题描述】:

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

我有三个这样的数组(这只是一个例子,不是实际的东西: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 但我不太擅长正则表达式。

【问题讨论】:

  • 解决大写问题:str_ireplace
  • 干杯会这样做,关于间距的任何想法?
  • 我没有看到间距问题。
  • 这似乎也适用于间距,但现在出现了另一个问题,如果我想用链接替换单词“apple”,它也会替换单词“apples”但不链接's',无论如何要解决这个问题?
  • 为此你需要一个正则表达式

标签: php regex


【解决方案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;

【讨论】:

  • 非常感谢,我将如何替换说“苹果”而不是“苹果”这个词?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多