3

当一个字符出现x次时,是否有一个能够替换的php函数?

例子

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

每 3 个逗号将附加 "\n\r"

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

我写了这个。

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]+"\n\r"+$string[$i+1]; 
        }
        return $string;
    }
4

3 回答 3

2

你可以使用chunk_split()

echo chunk_split($string, 6, '<br />'); //6 because after every third comma so count characters

这似乎与任意数量的字母有关::

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

function split_me($str, $delim, $pos) {
    return implode($delim."<br />", array_map(function($arr) use ($delim) {
          return implode($delim, $arr);
    }, array_chunk(explode($delim, $str), $pos)));
}
echo split_me($string,",", 3);
于 2013-09-30T04:26:08.537 回答
2

无论逗号之间有多少个字母,这都会起作用(它会在找到的每个 $count 逗号后添加一个中断):

function addLineBreaks($string,$char,$count) {
    return preg_replace("/(?:[^$char]+$char){{$count}}/","\\0<br />",$string);
}

示例用法:

echo addLineBreaks("a,b,c,d,e,f,g,h,i,j,k,l",",",3);
于 2013-09-30T04:33:06.020 回答
0

像这样的东西可以工作(非常粗糙):

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 .= "\r\n";           
        }
    }

    return $output;
}

像这样使用它:

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
于 2013-09-30T04:35:33.350 回答