Search code examples
phparraysstringpositionaddition

How to insert character in a string at a specific position?


$str="Hello From Other Side ";
$add = rand(20,50);

How can I insert a number or character as (25) after every character in a string at a specific position?

result

He25llo Fr25om Ot26her S25ide

Thank you


Solution

  • You can use the substr() function!

    If u want to insert 25 inside $str="Hello From Other Side "; at the position 2!

    U can do

    $pos=2;
    $new_string= substr($str, 0, $pos). "25" . substr($str, $pos);
    

    and the results would be:

    "He25llo From Other Side "