-1

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] = "-"; // maybe it's the problem
var_export($char);

It's not working -_-

  • 1
    Split your problem up into small steps, research and solve each step in turn. 1) [How do I get the first character of a string?](https://stackoverflow.com/questions/33890810/how-to-get-the-first-character-of-string-in-php) 2) [How do I get the last n characters of a string?](https://stackoverflow.com/questions/10542310/how-can-i-get-the-last-7-characters-of-a-php-string) 3) [How do I combine 2 strings?](https://stackoverflow.com/questions/8336858/how-can-i-combine-two-strings-together-in-php). – Don't Panic Jun 30 '23 at 05:54
  • 1
    Even better, why not start with the docs!? Super-charge your future development by getting an idea of what is available and skim [the list of PHP string functions](https://www.php.net/manual/en/ref.strings.php). – Don't Panic Jun 30 '23 at 05:56
  • 1
    im sorry I jumped to the stackoverflow without reading in the docs –  Jun 30 '23 at 06:20
  • 1
    There is no space in `$id_number`. – Markus Zeller Jun 30 '23 at 08:15

2 Answers2

0

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)

Adrian Kokot
  • 2,172
  • 2
  • 5
  • 18
0

You may try this with substr_replace() :

$id_number = !strpos($id_number, '-') ? substr_replace($id_number, '-',1,0) : $id_number;
echo $id_number;