doure8758 2013-09-30 03:54
浏览 30
已采纳

替换字符串每3个字符出现在PHP中

Is there a php function that is able to replace when a character appear x time?

example

$string="a,b,c,d,e,f,g,h,i,j,k,l";

every 3 commas will append " "

a,b,c,
d,e,f,
g,h,i,
j,k,l

I have written this.

function addBreaks($string,$char,$count) {  
    $ii = 0;
    for ( $i = 0; $i < strlen($string); $i++){  
        if ($string[$i] == $char){
            $ii++;      
            }
        if ($ii == $char){      
            $ii = 0;

            }
        $string = $string[$i]+"
"+$string[$i+1]; 
        }
        return $string;
    }
  • 写回答

3条回答 默认 最新

  • doushi5117 2013-09-30 04:35
    关注

    Something like this could work (very rough):

    function addLineBreaks( $str, $n = ',', $x = 3 ) {
        $sArr = str_split( $str );
        $output = '';
        $occ = 0;
        foreach( $sArr as $k=>$v ) {
            $output .= $v;          
            if( $v == $n ) {
                $occ++;
                if( $occ%$x == 0 ) $output .= "
    ";           
            }
        }
    
        return $output;
    }
    

    Use it like:

    header("Content-Type:text/plain");
    echo addLineBreaks( "a,b,c,d,e,f,g,h,i,j,k,l" );
    // outputs:
    //a,b,c,
    //d,e,f,
    //g,h,i,
    //j,k,l
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?