How to replace every second space?

I want to replace every second space with " ," using preg_replace. And enter the line as follows:

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

should lead to the following conclusion:

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

thank

+3
source share
3 answers

You can use a combination of explode, array_chunk, array_mapandimplode

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

But he suggests that every word is shared by one space.

Another and probably simpler solution is preg_replaceas follows:

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

(\S+\s+\S+)\s (\S+), (\S+), , . .

, :

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

:

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

, :

// 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;
}

+4
    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
+1
source

Source: https://habr.com/ru/post/1775186/


All Articles