Hi, I have a string, and I want to remove every other character. Does anyone know the easiest way to do that?
<?php $my_string = "ansimation"; //expected result: asmto function char_skip($str) { $r = ""; for ($x =0; $x < strlen($str); $x++) { if($x % 2 == 0) $r .= $str[$x]; } return $r; } echo char_skip($my_string); ?> PHP:
you can do it even easier, without the modulo operator: <?php $my_string = "ansimation"; //expected result: asmto function char_skip($str) { $r = ""; for ($x =0; $x < strlen($str); $x+=2) { $r .= $str[$x]; } return $r; } echo char_skip($my_string); ?> PHP:
Yet another solution would be regular expression: function char_skip($str) { return preg_replace('/(.)./', '$1', $str); } PHP: