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

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.

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

You can use preg_replace with a capture group:

$devid = preg_replace('/^(ESP\d{1,2}+).+/', '$1', $devid);

This regex matches & captures the text that we want to keep in group #1 and in replacement we put back $1.

or without the capture group use match reset \K:

$devid = preg_replace('/^ESP\d{1,2}+\K.+/', '', $devid);

This regex matches text that we want to keep and then using \K we reset match info. In replacement we just use empty string.

RegEx Demo

Note that {1,2}+ matches between 1 and 2 times, as many times as possible, without giving back.

I believe you need the word boundary \b.

preg_match("/\bESP\d{1,2}\b/", $devid, $match);

The word boundary makes sure it matches a word that starts with ESP and ends with one or two digits.