Maisam Mansour
Maisam Mansour

Reputation: 97

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.

Upvotes: 1

Views: 1231

Answers (4)

mickmackusa
mickmackusa

Reputation: 47883

You don't need capture groups or backreferences. Just forget the digits with \K after matching them. The .* will match the rest of the string and only this part will be removed.

$trimmed = preg_replace('/\d+\K.*/', '', $string);

Upvotes: 0

Kiarash Razaghi
Kiarash Razaghi

Reputation: 16

Sample code:

$str = "abc123efg567jjjj";
echo preg_replace("/([^0-9]*[0-9]*)(.*)/", "$1", $str);

Sample output:

abc123

Upvotes: 0

Haprog
Haprog

Reputation: 853

In your while loop, try using mb_substr($string, $i, 1) to get the character instead of $string[$i]. I think the latter only returns the single byte at byte index $i instead of the number $i character of a string with multibyte characters.

Upvotes: 2

jeroen
jeroen

Reputation: 91734

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

Upvotes: 5

Related Questions