$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 .
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.
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.
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 .
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With