skip to Main Content

I have lines of text that look like this…

My name is George 123123123

I like cheese and crackers 123456789

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

2

Answers


  1. You could try a simple regex:

    preg_replace('/.. ([0-9]{9})$/', ' - 1', 'My name is George 123123123')
    

    produces

    My name is Geor - 123123123
    
    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search