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

时间:2012-09-12 20:29:02

标签: php regex

我在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")

字符串的格式为:

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

我的目标是删除值766740,因为它只是垃圾。这些值可以包含单个,两个和三个数字。

下一步是从字符串中删除STEAM_0:1:20130600STEAM_0:1:55386073并将其捕获到一个新变量中。唯一的常数是STEAM_0:,其余的可以改变。

我仍在学习正则表达式,但我担心这对我来说有点复杂。一些指导意见是最值得赞赏的。

2 个答案:

答案 0 :(得分:0)

试试这个:(不擅长PHP,但这应该很接近,正则表达式应该有效)

<?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);
?>

使用代码here

播放
  • 正则表达式/\d{1,3}(?=\s*STEAM_0)/i匹配之前发生的数字 STEAM_0(正向前瞻)并用空字符串替换它们
  • 正则表达式/STEAM_0[^\s]+/i匹配所有STEAM_0个字词(不区分大小写)并打印出来 所有比赛的数组。

答案 1 :(得分:-1)

$ 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"
}