douyingzhan5905 2014-09-22 20:50
浏览 305
已采纳

找到第一组连续数字php正则表达式

I am fairly new to both php and regular expressions and am having trouble finding my solution. I am not sure if it because I do not know the terms to google or what, but here is my question:

I am trying to use PHP preg_match to find the first set of consecutive numbers in a string. 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

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.

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.

  • 写回答

2条回答 默认 最新

  • dpnvrt3119 2014-09-22 20:55
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化