[英]PHP Regex to Find Any Number at the Beginning of String
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.我正在使用 PHP,并希望能够创建一个正则表达式来查找并返回地址的街道号码部分。
Example:例子:
1234- South Blvd. 1234-南大道。 Washington D.C., APT #306, ZIP45234
华盛顿 D.C.,APT #306,ZIP45234
In the above example, only 1234 would be returned.在上面的示例中,只会返回 1234。
Seems like this should be incredibly simple, but I've yet to be successful.看起来这应该非常简单,但我还没有成功。 Any help would be greatly appreciated.
任何帮助将不胜感激。
Try this:尝试这个:
$str = "1234- South Blvd. Washington D.C., APT #306, ZIP4523";
preg_match("~^(\d+)~", $str, $m);
var_dump($m[1]);
string(4) "1234"
I know you requested regex
but it may be more efficient to do this without (I haven't done benchmarks yet).我知道您要求使用
regex
,但如果没有(我还没有完成基准测试),这样做可能会更有效。 Here is a function that you might find useful:这是您可能会发现有用的 function:
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));
如果您不希望这样,只需将
(&$str)
更改为($str)
并删除以下行: $str = substr($str, strlen($num));
. .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.