【问题标题】:PHP string find and replace until last instancePHP字符串查找和替换直到最后一个实例
【发布时间】:2011-12-27 23:07:09
【问题描述】:

我在数据库表中有一个字符串,用逗号分隔,即 this,is,the,first,sting

我想做但不知道如何将字符串输出如下: this, is, the, first and string

注意空格,最后一个逗号被“and”代替。

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    这可能是您的解决方案:

    $str = 'this,is,the,first,string';
    $str = str_replace(',', ', ', $str);
    echo preg_replace('/(.*),/', '$1 and', $str);
    

    【讨论】:

      【解决方案2】:

      第一次使用,本回答提供的功能:PHP Replace last occurrence of a String in a String?

      function str_lreplace($search, $replace, $subject)
      {
          $pos = strrpos($subject, $search);
      
          if($pos === false)
          {
              return $subject;
          }
          else
          {
              return substr_replace($subject, $replace, $pos, strlen($search));
          }
      }
      

      然后,您应该对文本执行一个通用的 str_replace 来替换所有其他逗号:

      $string = str_lreplace(',', 'and ', $string);
      str_replace(',',', ',$string);
      

      【讨论】:

        【解决方案3】:
        $words = explode( ',', $string );
        $output_string = '';
        for( $x = 0; $x < count($words); x++ ){
            if( $x == 0 ){
                $output = $words[$x];
            }else if( $x == (count($words) - 1) ){
                $output .= ', and ' . $words[$x]; 
            }else{
                $output .= ', ' . $words[$x];
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-05-05
          • 2016-01-31
          • 1970-01-01
          • 1970-01-01
          • 2014-05-13
          • 1970-01-01
          • 2016-05-23
          • 1970-01-01
          相关资源
          最近更新 更多