匹配后立即跟随PHP preg_replace数字

时间:2013-12-04 02:27:00

标签: php regex preg-replace preg-match

这是我将要使用的示例字符串:

john:4 40 4 guy:42 402 42 jack:6 666 8

我正在尝试匹配单词guy,并将以下三个数字替换为其他数据。这是我一直尝试的变种

$userString = "john:4 40 4 guy:42 402 42 jack:6 666 8";
$expression = "/guy.*?(\d+)/";
preg_replace($expression, 666666666, $userString);
echo $userString;

这不起作用,我有点迷失。

4 个答案:

答案 0 :(得分:1)

$userString = "john:4 40 4 guy:42 402 42 jack:6 666 8";
$userString = preg_replace('~guy:[^a-z]~i',666666666.' ', $userString);

答案 1 :(得分:1)

非常肯定到目前为止,没有一个答案给出了所需的输出,所以这是我的解释:

您希望42 402 42之后的所有三个号码guy:替换为666666666

$userString = 'john:4 40 4 guy:42 402 42 jack:6 666 8';
$userString = preg_replace('/(guy:)\d+\s+\d+\s+\d+/', '${1}666666666', $userString);
echo $userString;

输出:

john:4 40 4 guy:666666666 jack:6 666 8

答案 2 :(得分:0)

preg_replace()返回一个字符串,所以你只需将它分配给一个var:

$userString = "john:4 40 4 guy:42 402 42 jack:6 666 8";
$expression = "/guy.*?(\d+)/";
$userString = preg_replace($expression, 666666666, $userString);
echo $userString;

答案 3 :(得分:0)

在这种情况下,最好只做一个组合,preg_match& preg_replace计划。是的,它是杂耍,但它的工作原理和很明白。以下是使用此逻辑重新编写的代码:

// Your original user string.
$userString = "john:4 40 4 guy:42 402 42 jack:6 666 8";

// This basically grabs `guy:42 402`
$expression = "/guy:.*?\d{2}\s+(\d{3})/";

// This runs the regex.
preg_match($expression, $userString, $matches1);

// This takes `guy:42 402` and replaces the last 3 digits with `666666666`
$replacement = preg_replace("/\d{3}$/", 666666666, $matches1[0]);

// Then this matches the first `guy:42 402` & replaces it with `guy:42 666666666 `
$final = preg_replace("/".$matches1[0]."/", $replacement, $userString);

// Echo the `$final` string for review.
echo $final;