PHP Regex to Find Any Number at the Beginning of String

后端 未结 2 1702
别那么骄傲
别那么骄傲 2021-01-13 04:32

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. Washing

2条回答
  •  北海茫月
    2021-01-13 04:47

    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));.

提交回复
热议问题