How to remove every other character?

Discussion in 'PHP' started by bobby9101, Jun 28, 2007.

  1. #1
    Hi, I have a string, and I want to remove every other character. Does anyone know the easiest way to do that?
     
    bobby9101, Jun 28, 2007 IP
  2. ansi

    ansi Well-Known Member

    Messages:
    1,483
    Likes Received:
    65
    Best Answers:
    0
    Trophy Points:
    100
    #2
    
    <?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:
     
    ansi, Jun 28, 2007 IP
  3. UnrealEd

    UnrealEd Peon

    Messages:
    148
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #3
    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:
     
    UnrealEd, Jun 29, 2007 IP
  4. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #4
    Yet another solution would be regular expression:
    
    function char_skip($str)
    {
    	return preg_replace('/(.)./', '$1', $str);
    }
    
    PHP:
     
    nico_swd, Jun 29, 2007 IP
  5. bobby9101

    bobby9101 Peon

    Messages:
    3,292
    Likes Received:
    134
    Best Answers:
    0
    Trophy Points:
    0
    #5
    thanks guys
     
    bobby9101, Jun 29, 2007 IP