Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

php

$str = "helloworld";

I want to create string

$newStr = "h l o o l ";

So as you can see i want to replace the chars in positions , 2,4,6,8,10 (assuming first character is in position 1).

I can do something like this

<?php

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

echo $newStr;

?>

But is there a more easier way or a one line in built function available to do this task .

Thanks in advance .

like image 288
Kanishka Panamaldeniya Avatar asked Nov 02 '16 07:11

Kanishka Panamaldeniya


People also ask

How do you replace all occurrences of a character in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.

How do I replace all characters?

Use the replace() method to replace umlaut characters in JavaScript. The first parameter the method takes is the character you want to replace, and the second - the replacement string. The method returns a new string where the matches are replaced.

How replace all occurrences of a string in TypeScript?

To replace all occurrences of a string in TypeScript, use the replace() method, passing it a regular expression with the g (global search) flag. For example, str. replace(/old/g, 'new') returns a new string where all occurrences of old are replaced with new .


3 Answers

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.

like image 153
Ruslan Osmanov Avatar answered Sep 24 '22 03:09

Ruslan Osmanov


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.

like image 34
Ortho Avatar answered Sep 26 '22 03:09

Ortho


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;
like image 36
Blinkydamo Avatar answered Sep 26 '22 03:09

Blinkydamo