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

PHP – Help replacing specific characters in a string

I have lines of text that look like this…

My name is George 123123123

I like cheese and crackers 123456789

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

Each sentence can be any length but always ends with a space followed by 9 digits.

I need the sentences to end with, space hyphen space then the 9 digits.

BUT… you can’t change the length of the sentences.

I don’t want it changed to My name is George - 123123123

In this example, it should change to My name is Geor - 123123123

>Solution :

You can simply replace the portion of the string from the offset of the end of the string (-12 – the 9 for the number and the 3 for the space, hyphen and space)

So

$string = 'My name is George 123123123';
$string = substr_replace($string, ' - ', -12, 3);
echo $string;

gives

My name is Geor - 123123123
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