dongxibeng5324 2018-06-28 16:07
浏览 480
已采纳

如何匹配正则表达式,在匹配后删除所有内容

Say I have the following: preg_match("/ESP[0-9]?[0-9]/", $devid)

I want to match data such as the following:
$devid = "ESP1"
$devid = "ESP10"
$devid = "ESP78"

However, I don't want the string to contain anything that isn't matched in the regex. For example: $devid = "ESP100" would return ESP10
$devid = "ESP10234234" would return ESP10
$devid = "ESP78hello" would return ESP78

...and if there isn't a match, returning null (or equivalent).

In a way, I want to detect where preg_match finishes, and then remove the rest.

  • 写回答

3条回答 默认 最新

  • doufuhuang6981 2018-06-28 16:26
    关注

    You can use a third argument in preg_match like:

    preg_match('/ESP\d\d?/', $string, $matches);
    var_dump($matches[0] ?? NULL);
    

    In case nothing is found NULL will be output.

    Edit(cars10m):
    From testing in rextester.com I found that $matches is returned as an array of length 0, when nothing is found, see here: http://rextester.com/UUM57869

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

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用