开发者

How to replace every second white space?

I want replace every second white spac开发者_JAVA技巧e with "," using preg_replace. And input string like this:

$string = 'a b c d e f g h i';

should result in an output like this:

a b,c d,e f,g h,i

thanks


You can use a combination of explode, array_chunk, array_map and implode:

$words = explode(' ', $string);
$chunks = array_chunk($words, 2);
$chunks = array_map(function($arr) { return implode(' ', $arr); }, $chunks);
$str = implode(',', $chunks);

But it assumes that each word is separated by a single space.

Another and probably easier solution is using preg_replace like this:

preg_replace('/(\S+\s+\S+)\s/', '$1,', $string)

The pattern (\S+\s+\S+)\s matches any sequence of one or more non-whitespace characters (\S+), followed by one or more whitespace characters (\s+), followed by one or more non-whitespace characters, followed by one whitespace character, and replaces the last whitespace by a comma. Leading whitespace will be ignored.

So the matches will be in this case:

a b c d e f g h i
\__/\__/\__/\__/

These are then replaced as follows:

a b,c d,e f,g h,i


Since you want to search and replace characters you can do it as:

// function to replace every '$n'th occurrence of $find in $string with $replace.
function NthReplace($string,$find,$replace,$n) {
        $count = 0;
        for($i=0;$i<strlen($string);$i++) {
                if($string[$i] == $find) {
                        $count++;
                }
                if($count == $n) {
                        $string[$i] = $replace;
                        $count = 0;
                }
        }
        return $string;
}

Ideone Link


    function insertAtN($string,$find,$replace,$n) {
        $borken =  explode($find, $string);
        $borken[($n-1)] = $borken[($n-1)].$replace;
        return (implode($find,$borken));
    }

    $string ="COMPREHENSIVE MOTORSPORT RACING INFORMATION"; 
    print insertAtN($string,' ',':',2) 
    //will print
    //COMPREHENSIVE MOTORSPORT:RACING INFORMATION
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜