php - How to replace every second white space? -


i want replace every second white space "," using preg_replace. , input string this:

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

should result in output this:

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

thanks

you can use combination of explode, array_chunk, array_map , implode:

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

but assumes each word separated single space.

another , easier solution using preg_replace this:

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

the pattern (\s+\s+\s+)\s matches sequence of 1 or more non-whitespace characters (\s+), followed 1 or more whitespace characters (\s+), followed 1 or more non-whitespace characters, followed 1 whitespace character, , replaces last whitespace comma. leading whitespace ignored.

so matches in case:

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

these replaced follows:

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

Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -