【问题标题】:PHP str.replace: two or more at one time?PHP str.replace:一次两个或多个?
【发布时间】:2012-05-11 04:52:45
【问题描述】:

假设我有一个这样的字符串:

$str = "{aaa,aa,a,aaaaaaaa,aaaaaaa,aaaaaaa}";

我想只使用一次str_replace 删除{}.. 可以吗?

我试过了

$str = str_replace('}', '{', '', $str);

$str = str_replace('}'&'{', '', $str);

$str = str_replace('}'||'{', '', $str);

$str = str_replace('}''{', '', $str);

没有任何效果...

【问题讨论】:

  • Str_replace for multiple items 的可能重复项
  • 只是一个旁注,如果你只想删除左右两侧,你可能想要trim($input, '{}');,它更短一点,更重要。什么数据?

标签: php str-replace


【解决方案1】:
$str = str_replace(array('}', '{'), '', $str);

str_replace 接受数组作为其第一个和第二个参数

【讨论】:

    【解决方案2】:

    你可以给一个数组来替换 str 看看

    $search = array("}", "{");
    $text= str_replace($search, "", $text);
    

    在这里阅读:str-replace

    【讨论】:

      【解决方案3】:
      str_replace (array('}', '{'), '', $str);
      

      【讨论】:

        【解决方案4】:
        $str = str_replace(array('{', '}'), '', $str);
        

        【讨论】:

          【解决方案5】:

          您想要做的是使用 preg_replace 函数,而不是使用正则表达式一次替换多个项目。你想做的事情可以通过以下方式完成:

          $str = preg_replace('/({|})/', '', $str);
          

          【讨论】:

          • 或者[{}]稍微好一点
          【解决方案6】:

          $search = array("}", "{"); $text= str_replace($search, "", $text);

          你可以阅读更多:-http://php.net/manual/en/function.str-replace.php

          例子

          <?php
          // Order of replacement
          $str     = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
          $order   = array("\r\n", "\n", "\r");
          $replace = '<br />';
          
          // Processes \r\n's first so they aren't converted twice.
          $newstr = str_replace($order, $replace, $str);
          
          // Outputs F because A is replaced with B, then B is replaced with C, and so on...
          // Finally E is replaced with F, because of left to right replacements.
          $search  = array('A', 'B', 'C', 'D', 'E');
          $replace = array('B', 'C', 'D', 'E', 'F');
          $subject = 'A';
          echo str_replace($search, $replace, $subject);
          
           // Outputs: apearpearle pear
          // For the same reason mentioned above
          $letters = array('a', 'p');
          $fruit   = array('apple', 'pear');
          $text    = 'a p';
          $output  = str_replace($letters, $fruit, $text);
          echo $output;
          ?>
          

          【讨论】:

            猜你喜欢
            • 2013-12-18
            • 1970-01-01
            • 1970-01-01
            • 2016-01-11
            • 1970-01-01
            • 2016-10-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多