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

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

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条)

报告相同问题?