Home > front end >  php preg_match - pattern for number at end of string, always preceded by space, in turn preceded by
php preg_match - pattern for number at end of string, always preceded by space, in turn preceded by

Time:11-11

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?

CodePudding user response:

You can try this approach:

preg_match("/^\S.* (\b\d )$/", $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.

CodePudding user response:

You may use this regex:

^\S.*\b\d $

RegEx Demo

RegEx Details:

  • ^: Start
  • \S: Match a non-whitespace
  • .*: Match 0 or more of any character
  • \b\d : Match any integer number
  • $: End
  • Related