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

preg_match('#^(.)* (d*)$#', $str, $matches);

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

I thought about reversing the string and doing this

preg_match('#^(d*)(s*)(.*)$#', strrev($str), $matches);
var_dump(strrev($matches[1]));

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:

preg_match("/^S.* (bd+)$/", $str, $matches);
echo end($matches)."n";

For instance if you use the following variable:

$str = "1234 lkjsdhf ldjfh  1223";

The call to end($matches) will return 1223

Whereas if you use the following variable:

$str = " 1212";

call to end($matches) will remain empty.

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