【问题标题】:str_replace in phpphp中的str_replace
【发布时间】:2010-02-21 19:58:08
【问题描述】:

我有一个可以同时保存所有这些值的长字符串:

hello<!>how are you? <!>I am fine<!> What is up? <!> Nothing!

我需要找到所有这些可能性:

' <!> '
' <!>'
'<!> '
'<!>'

并将它们替换为“\n”

用php中的str_replace可以实现吗?

【问题讨论】:

    标签: php str-replace


    【解决方案1】:

    如果您只有这 4 种可能性,是的,那么您可以通过 str_replace 做到这一点。

    $str = str_replace( array( ' <!> ', ' <!>', '<!> ', '<!>' ), "\n", $str );
    

    是的,但是如果有两个空格呢?还是标签?您是否为每个添加了空间案例?

    您可以为每种情况添加特殊情况,或使用正则表达式:

    $str = preg_replace( '/\s*<!>\s*/', "\n", $str );
    

    【讨论】:

      【解决方案2】:

      当然,您可以通过 4 次调用 str_replace 来实现此目的。 编辑:我错了。您可以在str_replace 中使用数组。

      $str = str_replace(' <!> ', "\n", $str);
      $str = str_replace(' <!>',  "\n", $str);
      $str = str_replace('<!> ',  "\n", $str);
      $str = str_replace('<!>',   "\n", $str);
      

      还可以考虑使用strtr,它可以一步完成。

      $str = strtr($str, array(
          ' <!> ' => "\n",
          ' <!>'  => "\n",
          '<!> '  => "\n",
          '<!>'   => "\n"
      ));
      

      或者您可以使用regular expression

      $str = preg_replace('/ ?<!> ?/', "\n", $str);
      

      【讨论】:

      • @codeholic:你不需要 4 次调用 str_replace。他想替换为“\n”
      【解决方案3】:

      你当然可以像这样用 str_replace 做到这一点:

      $needles = array(" <!> ","<!> "," <!>","<!>");
      $result = str_replace($needles,"\n",$text);
      

      【讨论】:

      • 是的,但是如果有两个空格呢?还是标签?你会为每个人添加一个空间案例吗?
      • @e-satis:要求很明确。如果 OP 的意思不是他所问的或遗漏了一些细节,他应该编辑问题。
      【解决方案4】:

      您不能仅使用str_replace 来做到这一点。使用explodestripimplode 的组合,或者使用用户preg_replace

      【讨论】:

        【解决方案5】:

        编辑:preg_replace('/\s*&lt;!&gt;\s*', PHP_EOL, $string); 应该更好。

        当然,如果您的示例完整,str_replace('&lt;!&gt;', "\n", $string);

        【讨论】:

          【解决方案6】:

          你可以使用:

          //get lines in array
          $lines = explode("<!>", $string);
          //remove each lines' whitesapce
          for(i=0; $i<sizeof($lines); $i++){
              trim($lines[$i]);
          }
          //put it into one string
          $string = implode("\n", $lines)
          

          这有点乏味,但这应该可以工作(还删除了两个空格和制表符)。 (没有测试代码,所以可能有错误)

          【讨论】:

            【解决方案7】:

            这有点整洁:

            $array = explode('<!>', $inputstring);
            foreach($array as &$stringpart) {
              $stringpart = trim($stringpart);
            }
            $outputstring = implode("\r\n", $array);
            

            【讨论】:

              猜你喜欢
              • 2021-09-02
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2023-04-02
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多