Skip to content
Advertisement

php preg_match – pattern for number at end of string, always preceded by space, in turn preceded by any characters?

I am trying to extract a number from a string. The string is a filename, will be variable in its contents, but will end with a space followed by a number.

So strings like a b 1212, a 1212. I am not sure if filenames ever end up with a whitespace at the beginning, but something like 1212 should not produce a match.

I am using so far

JavaScript

but that returns a match for case of something like 1212.

I thought about reversing the string and doing this

JavaScript

and checking if $matches[1] != '' and that seems to work, but I am trying to better understand regex, so that I can do this without the reverse, and figure out proper pattern for the case get number at end of string, which is always preceded by a space, and where that space in turn is always preceded but anything.

Ideas?

Advertisement

Answer

You can try this approach:

JavaScript

For instance if you use the following variable:

JavaScript

The call to end($matches) will return 1223

Whereas if you use the following variable:

JavaScript

call to end($matches) will remain empty.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement