【问题标题】:Replace (ss) with something else用其他东西替换(ss)
【发布时间】:2013-04-19 06:52:06
【问题描述】:

我在 PHP 中遇到了替换字符串中的 (ss) 的问题。

$string = 'I want a new (ss) now!';
$newString = preg_replace('\(ss\)', 'car', $string);

我期待 $newString 变成:

我现在想要一辆新车!

我在这里做错了什么?

【问题讨论】:

    标签: php regex preg-replace


    【解决方案1】:

    您的问题是您的正则表达式没有delimiters

    但是,鉴于您没有使用任何正则表达式功能,您最好使用str_replace()

    【讨论】:

      【解决方案2】:

      使用str_replace

      $string = 'I want a new (ss) now!';
      $newString = str_replace('(ss)', 'car', $string);
      

      示例http://codepad.org/2wcYtL8E

      输出

      我现在想要一辆新车!

      编辑

      preg_replace 为例

      http://codepad.org/CFmSDTjR

      $string = 'I want a new (ss) now!';
      $newString = preg_replace('$\(ss\)$', 'car', $string);
      

      输出

      我现在想要一辆新车!

      【讨论】:

      • 谢谢!我是正则表达式的新手,我觉得用它会很好,呵呵
      • @mnstrflkrn 你不应该使用这些东西,因为你认为它们不错。如果它们是适合这项工作的工具,您应该使用它们。
      【解决方案3】:
      $newString = str_replace("ss", "car", $string);
      

      【讨论】:

        【解决方案4】:

        使用 str_replace()

        $newString = str_replace("(ss)", "car", $string);
        

        【讨论】:

          猜你喜欢
          • 2016-07-03
          • 1970-01-01
          • 1970-01-01
          • 2019-07-20
          • 1970-01-01
          • 2018-10-28
          • 2011-04-13
          • 1970-01-01
          • 2022-10-09
          相关资源
          最近更新 更多