JayEdgar
JayEdgar

Reputation: 196

Get first group of numbers with regex

I need to grab the first group of numbers from a street address. The address might start with the number, and it might not; and there might be other numbers.

For both examples below, I want to get "123" as the result:

123 E 9th St

E 123 9th St

I've tried a number of things, and can't quite get it. Help is appreciated.

[edit] sorry for the lack of information. Here's what I've tried:

$StreetNum = preg_replace( '/^(|\\s)([0-9]+)($|\\s)/', '', $StreetName );
$StreetNum = preg_replace( '/^([0-9]+)?/', '', $StreetName );
$StreetNum = preg_replace( '/^([0-9]+)?/', '', $StreetName );

Upvotes: 2

Views: 4293

Answers (2)

Kumar
Kumar

Reputation: 1217

Well, you can use this regex syntax, (\d){3}

preg_match("/(\d){3}/", "123 E 9th St",$m);
echo $m[0];

output: 123

It can use to get 123 from

123 E 9th St

E 123 9th St

9th St E 123

Any digits group by 3. I have write it by looking at your subject. If you want 123 or other digits. But they should group by 3. Here I have done https://www.regex101.com/r/opuu2n/1

Upvotes: 0

shoieb0101
shoieb0101

Reputation: 1582

Try this

$string = "E 123 9th St";
$pattern = "/[0-9]+/";
if (preg_match($pattern, $string, $matches)) {
    var_dump($matches[0]);
 }

Upvotes: 3

Related Questions