PHP Regex to Find Any Number at the Beginning of S

2020-03-23 11:25发布

I'm using PHP, and am hoping to be able to create a regex that finds and returns the street number portion of an address.

Example:

1234- South Blvd. Washington D.C., APT #306, ZIP45234

In the above example, only 1234 would be returned.

Seems like this should be incredibly simple, but I've yet to be successful. Any help would be greatly appreciated.

标签: php regex
2条回答
够拽才男人
2楼-- · 2020-03-23 11:57

Try this:

$str = "1234- South Blvd. Washington D.C., APT #306, ZIP4523";
preg_match("~^(\d+)~", $str, $m);
var_dump($m[1]);

OUTPUT:

string(4) "1234"
查看更多
戒情不戒烟
3楼-- · 2020-03-23 12:14

I know you requested regex but it may be more efficient to do this without (I haven't done benchmarks yet). Here is a function that you might find useful:

function removeStartInt(&$str)
{
    $num = '';
    $strLen = strlen($str);
    for ($i = 0; $i < $strLen; $i++)
    {
        if (ctype_digit($str[$i]))
            $num .= $str[$i];
        else
            break;
    }
    if ($num === '')
        return null;
    $str = substr($str, strlen($num));
    return intval($num);
}

It also removes the number from the string. If you do not want that, simply change (&$str) to ($str) and remove the line: $str = substr($str, strlen($num));.

查看更多
登录 后发表回答