skip to Main Content

I want to insert a character after the first character in a word using PHP like this, ID: R-CDA12345 to first character in this ID serves as the type of an item so I can easily know where it is from.

I tried a method like this,

$id_number = "RCDA12345";

$char = explode(' ', $id_number);
$char[1] = "-";
var_export($char);

It’s not working -_-

2

Answers


  1. You can do that with substr:

    $char = $id_number[0] . '-' . substr($id_number, 1);
    

    Or with substr_replace:

    $char = substr_replace($id_number, '-', 1, 0);
    

    Which can also insert string in string by given offset and with given length (3rd and 4th parameters)

    Login or Signup to reply.
  2. You may try this with substr_replace() :

    $id_number = !strpos($id_number, '-') ? substr_replace($id_number, '-',1,0) : $id_number;
    echo $id_number;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search