Keith D Kaiser
Keith D Kaiser

Reputation: 1036

How do I use regex in PHP to find a number surrounded by spaces?

With regex/PHP I'm trying to extract a number from a sting, but only if the number has a blank space before it and another after it.

Right now I have this:

$tacNO = number_format(intval(preg_replace('/[^0-9.]/','',$row[tactical])));

It works to get the number, but I need to adjust the regedit to test for the included spaces, and return only the number. Can that be done using lookbehind and lookahead? What would accomplish that?

Upvotes: 2

Views: 463

Answers (2)

PrivatePorkchop
PrivatePorkchop

Reputation: 71

A regex like \s[0-9]+\s would capture any number with a white-space on either side. If you want to make sure the characters on either side are spaces (not tabs etc.) then use this instead: [ ][0-9]+[ ] If you want to match numbers that only have white-space on one side use the * quantifier after the white-space identifiers.

Like lagripe said, a capturing group would probably be the best way to do this. You can use a capturing group by surrounding the desired part with parentheses: [ ]([0-9]+)[ ]. Alternatively, you can add a non-capturing group to the spaces: (?:[ ])[0-9]+(?:[ ]). What this does is uses them to match the string, but ignores them when giving the output.

If you want to test out your regex strings, the website regex101.com is my personal favorite.

Upvotes: 3

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521289

You could use lookarounds as follows:

$num = preg_match("/(?<=\s)\d+(?=\s)/", $row[tactical], $matches);
$tacNO = number_format(intval($matches[0]));

Or, you could use explicit spaces in the pattern and instead use a capture group to isolate the number match:

$num = preg_match("/\s+(\d+)\s+/", $row[tactical], $matches);
$tacNO = number_format(intval($matches[1]));

Upvotes: 2

Related Questions