Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Insert a character after a first character in PHP

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 -_-

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading