如何从字符串中删除特定数字?

I have this string in PHP:

Hopelessly Incredible |SPG:M| 766 STEAM_0:1:20130600 " banned "A
Blatantly Obvious Hacker 740 STEAM_0:1:55386073 " (minutes "0")
(reason "Multi-Hack")

The Format of the string is:

Name1 Number(0-3 digits) Steam_0:x:xxxx offense (banned/kicked/mute etc) Name2 Number(0-3 digits) Steam_0:x:xxxx time reason

My goal is to remove the values 766 and 740 because it is just garbage. Those values can have single, double, and triple digits.

The next step would be to strip STEAM_0:1:20130600 and STEAM_0:1:55386073 out of the string and capture it in a new variable. The only constant is STEAM_0:, the rest can change.

I am still learning regex but I fear this is a bit complicated for me to do. Some guidance would be most appreciative.

$ cat scratch.php
<?php
$s = 'Hopelessly Incredible |SPG:M| 766 STEAM_0:1:20130600 " banned "A Blatantly Obvious Hacker 740 STEAM_0:1:55386073 " (minutes "0") (reason "Multi-Hack")';

$s = preg_replace('@\d+ (STEAM_\d:)@', '\1', $s);
preg_match_all('@(STEAM_\d:\d+:\d+)@', $s, $matches);
var_dump($s, $matches[1]);


$ php scratch.php
string(142) "Hopelessly Incredible |SPG:M| STEAM_0:1:20130600 " banned "A Blatantly Obvious Hacker STEAM_0:1:55386073 " (minutes "0") (reason "Multi-Hack")"
array(2) {
  [0]=>
  string(18) "STEAM_0:1:20130600"
  [1]=>
  string(18) "STEAM_0:1:55386073"
}

Try this: (not good at PHP but this should be close and regexes should work)

<?php
$sourcestring='Hopelessly Incredible |SPG:M| 766 STEAM_0:1:20130600 " banned "A Blatantly Obvious Hacker 740 STEAM_0:1:55386073 " (minutes "0") (reason "Multi-Hack")';
$replacedstring = preg_replace('/\d{1,3}(?=\s*STEAM_0)/i','',$sourcestring);
echo $replacedstring;
preg_match_all('/STEAM_0[^\s]+/i',$replacedstring,$matches);
echo "<pre>".print_r($matches,true);
?>

Play with the code here


  • Regex /\d{1,3}(?=\s*STEAM_0)/i matches numbers occuring before STEAM_0 (positive lookahead) and replaces them with an empty string
  • Regex /STEAM_0[^\s]+/i matches all STEAM_0 words (case-insensitive) and prints the array of all matches.