Easiest way to replace all characters in even positions in a string.

Firstly you can increase your counter by two, so you don't have to check if it's odd. Secondly because strings are treated like char arrays you can access a char at position $i with $str[$i].

$str = "Hello World";
$newStr = $str;
for($i = 1; $i < strlen($str); $i += 2) {
  $newStr[$i] = ' ';
}
echo $newStr;

Have a Nice day.

[Edit] Thanks ringo for the hint.


It is easily done with a regular expression:

echo preg_replace('/(.)./', '$1 ', $str);

The dot matches a character. Every second character is replaced with a space.


Similar but using generator

$str = 'helloworld';
$newstr ='';
foreach(range($str, strlen($str)-1, 2) as $i){
$newstr.=$str[$i].' ';
}

Try this, a little shorter then yours but is a one-liner as you asked.

$str    = 'helloworld';
$newStr = '';
for( $i = 0; $i < strlen( $str ); $i++) { $newStr .= ( ( $i % 2 ) == 0 ? $str[ $i ] : ' ' ); }
echo $newStr;

Tags:

Php

String