Insert Character into String?

Discussion in 'PHP' started by tin2mon, Oct 18, 2010.

  1. #1
    I have a $string and want to loop through inserting characters inbetween the letters. What's the best function to do this in php?

    I apologise if I'm being a muppet.
     
    tin2mon, Oct 18, 2010 IP
  2. lukeg32

    lukeg32 Peon

    Messages:
    645
    Likes Received:
    19
    Best Answers:
    1
    Trophy Points:
    0
    #2
    There's loads of ways to do this; keeping it simple, something like the following;


    
    $string = "This is my string";
    $newstring = "";
    
    for($x=0; $x<strlen($string);$x++)
      {
      $newstring .= $string[$x];
      if($x != strlen($string)-1)
        $newstring .= "CHAR TO INSERT";
      }
    
    PHP:
    If you have more specific requirements, let me know
     
    lukeg32, Oct 18, 2010 IP
  3. mikecampbell

    mikecampbell Peon

    Messages:
    26
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    You could also do something like:
    
    $string = preg_replace("/([a-z])\B/i", "\$1$insert", $string);
    
    PHP:
    You can run this function here:
    http://www.exorithm.com/algorithm/view/insert_into_words
     
    mikecampbell, Oct 19, 2010 IP
  4. sinha.sidhi

    sinha.sidhi Peon

    Messages:
    50
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    function stringrpl($x,$r,$str)
    {
    $out = "";
    $temp = substr($str,$x);
    $out = substr_replace($str,"$r",$x);
    $out .= $temp;
    return $out;
    }

    $test = stringrpl(2,"c",$test);
    echo $test;
     
    sinha.sidhi, Aug 29, 2011 IP