phpregexnumberspreg-replacetruncation

Remove all characters after the first occurring integer


I need to remove everything after the first occurrence of a number in a string, but the number must remain. I'm having trouble keeping the number when I write this:

preg_replace('/[0-9].*/', '', $string); 

It removes everything including the number.


Solution

  • If your first replacement already works but removes too much, you can capture the number and put it back in:

    preg_replace('/([0-9]+).*/', '$1', $string); 
                   ^      ^       ^^ put the captured value back