用相同的数字替换RegEx中的数字

时间:2014-11-05 10:17:57

标签: php regex

<?php
function rg($str) {
    $p = '/\[pattern[0-9]\:[a-zA-Z]{3,10}\]/';
    $r = '[pattern[0-9]]';
    $str = preg_replace($p, $r, $str);
    return $str;
}

$s = "[pattern1:reverse] This is my test [pattern1:shift] String for [pattern3:nitro] Reg Ex [pattern2:reverse]";

echo rg($s);

这个输出将是

[pattern[0-9]] This is my test [pattern[0-9]] String for [pattern[0-9]] Reg Ex [pattern[0-9]]

但是我试图替换与模式相关的数字。所以输出将是这样的:

[pattern1] This is my test [pattern1] String for [pattern3] Reg Ex [pattern2]

任何提示?

2 个答案:

答案 0 :(得分:1)

试试这个:

function rg($str) {
    $p = '/(\[pattern[0-9])\:[a-zA-Z]{3,10}\]/';
    $r = '$1]'; # $1 contains what tou will catch inside the  paranthesis
    $str = preg_replace($p, $r, $str);
    return $str;
}

希望有所帮助:)

答案 1 :(得分:0)

(?<=pattern)(\d+)[^\]]*

试试这个。$1。见。演示。

http://regex101.com/r/iZ9sO5/4