讨论数量:
<?php
$string = 'google 123, 456';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '$0 - $1 - $2 - $3';
echo preg_replace($pattern, $replacement, $string);
?>
输出:
google 123, 456 - google - 123 - 456
每个这样的引用将被匹配到的第n个捕获子组捕获到的文本替换。 n可以是0-99,\0和$0代表完整的模式匹配文本,也就是整串字符串
$1
, $2
… $n
在正则表达式中,replaces 是对括号中包含的匹配项的引用。 $0
将是整个匹配,$1
是第一个带括号的捕获,$2
是第二个带括号的捕获,这样依此类推。
<?php
function replace(string $str)
{
// str => 18596854156@163.com
return preg_replace('/(.*)@(\d+).([a-z]+)/', '$1-$2-$3', $str);
// output => 18596954156-163-com
}
针对上面的例子:
- $0 是
$str
- $1 是
(.*)
- $2 是
(\d+)
- $3 是
([a-z]+)
具体参阅 docs,特别是该函数的 replace 参数
推荐文章: