[英]Find first set consecutive numbers php regex
I am fairly new to both php and regular expressions and am having trouble finding my solution. 我对php和正则表达式都相当陌生,并且在寻找解决方案时遇到了麻烦。 I am not sure if it because I do not know the terms to google or what, but here is my question:
我不确定是否可以,因为我不知道Google的术语或其他术语,但这是我的问题:
I am trying to use PHP preg_match to find the first set of consecutive numbers in a string. 我正在尝试使用PHP preg_match查找字符串中的第一组连续数字。 What I mean by consecutive numbers is ANY string where it is uninterrupted numbers.
我所说的连续数字是任何不间断数字的字符串。
ex. 恩。
'abc123abc' matches: 123 'ghdfk 1 23abc' matches: 1 '2475xyz' matches: 2475 'abc 456 789' matches: 456 'abc123abc'比赛:123'ghdfk 1 23abc'比赛:1'2475xyz'比赛:2475'abc 456 789'比赛:456
I have been looking through regular-expressions.info and google for terms similar to my question topic, but they all seem to return searches for people looking for repeating numbers of specific lengths. 我一直在通过regular-expressions.info和google搜索与我的问题主题相似的术语,但是它们似乎都返回了寻找重复特定长度数字的用户的搜索。
I am trying to parse an address string to the best of my ability, even though it might be horribly entered. 我试图尽我所能来解析地址字符串,即使可能输入的内容很糟。
Things I have tried so far that aren't working are in my code: 我到目前为止尝试过的不起作用的事情在我的代码中:
<?php
#$addr = '12-3 3rd street'; #1st Test
$addr = 'RR 3 Box 8411'; #2nd Test
#$addr = '480jacksonrd'; #3rd Test
#$addr = 'N2626prociousmayselrd'; #4th Test
#list($our['StreetNum'], $our['StreetName']) = explode(" ", $our['Address'], 2);
#preg_match('/.+(?=[^0-9])/s',$addr,$Matches);
#preg_match('/[0-9]*/',$addr,$Matches);
preg_match('/(?<=\[^0-9]).+?(?=[^0-9])/s',$addr,$Matches);
$our['StreetNum'] = $Matches[0];
$our['StreetNum'] = preg_replace("/[^0-9]/", "", $our['StreetNum']);
echo ('First Match?: ' . $Matches[0] . '<br>'); #For Testing
echo ('Second Match?: ' . $Matches[1] . '<br>'); #For Testing
echo ('StrLen of StreetNum: ' . strlen($our['StreetNum']) . '<br>');
echo ('StrPos of StreetNum: ' . strpos($addr,$our['StreetNum']) . '<br>');
$our['StreetName'] = substr($addr, strlen($our['StreetNum'])+strpos($addr,$our['StreetNum']));
echo ('Street Original: ' . $addr . '<br>');
echo ('Street Number: ' . $our['StreetNum'] . '<br>');
echo ('Street Name: ' . $our['StreetName'] . '<br>');
?>
Any help or direction would be greatly appreciated. 任何帮助或指示将不胜感激。
/[0-9]+/
as preg_match
should be enough. /[0-9]+/
作为preg_match
应该足够了。 You search for any 1 or more numbers. 您搜索任何1个或多个数字。
preg_match('/[0-9]+/', $addr, $Matches)
Or 要么
preg_match('/\d+/', $addr, $Matches)
You're overthinking. 你太想了。 Try this:
尝试这个:
if preg_match('/\d+/', $my_string, $matches)
return $matches[0];
You just need to search for digits, and return the match. 您只需要搜索数字,然后返回匹配项即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.