【问题标题】:search string for specific word and replace it搜索特定单词的字符串并替换它
【发布时间】:2011-04-13 18:20:49
【问题描述】:

我认为这是我需要的正则表达式。

我有一个文本输入,用户可以在其中搜索我的网站。 他们可能会在搜索短语之间使用“ELLER”这个词,在英语中等于“OR”。

但是,我的搜索引擎需要英文,所以我需要将查询字符串中的所有 ELLER 替换为 OR

我该怎么做?

顺便说一句,是php...

谢谢

【问题讨论】:

    标签: php regex search


    【解决方案1】:
    <?php
    // data
    $name = "Daniel";
    $order = 132456;
    
    // String to be searched
    $string = "Hi [name], thank you for the order [order_id]. The order is for [name]";
    
    // replace rules - replace [name] with $name(Danile) AND [order_id] with $order(123456)
    $text_to_send = str_replace(array('[name]', '[order_id]'), array($name, $order), $string);
    
    // print the result
    echo $text_to_send;
    

    “嗨,Damiel,谢谢你的订单 123456。订单是给丹尼尔的”

    【讨论】:

      【解决方案2】:

      还应注意,您还可以将 str_replace 传递给要更改的值数组和要更改的值数组,例如:

      str_replace(array('item 1', 'item 2'), 'items', $string);

      str_replace(array('item 1', 'item 2'), array('1 item', '2 item'), $string);

      【讨论】:

        【解决方案3】:

        如果您要替换特定的单词,则不需要正则表达式,您可以改用str_replace

        $string = str_replace("ELLER", "OR", $string);
        

        当您要查找的内容不是动态的时,使用 PHP 的字符串函数将比使用正则表达式更快。

        如果您想确保 ELLER 仅在全字匹配时被替换,并且不包含在另一个单词中,您可以使用 preg_replaceword boundary 锚点 (\b):

        $string = preg_replace('/\bELLER\b/', 'OR', $string);
        

        【讨论】:

          【解决方案4】:
          str_replace("ELLER", "OR", $string);
          

          http://php.net/manual/de/function.str-replace.php

          【讨论】:

          • 我同意,使用 str_replace。它比使用正则表达式要快得多。
          • 这样但使用字符串" ELLER "" OR "(注意空格)
          • 听从 Segfault 的建议,否则搜索“Helen Keller”或“Uri Geller”将无法正常工作
          • @Segfault 空格不是描述单词的唯一方法(其他可能是标点符号或字符串的开头或结尾)。没有正则表达式,你不能真正有效地匹配完整的单词。
          猜你喜欢
          • 2020-07-09
          • 1970-01-01
          • 2015-09-25
          • 1970-01-01
          • 2013-09-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-14
          相关资源
          最近更新 更多