2015-11-25 35 views
1

我想将每个\x替换为$matches[x],其中x是一个数字。如何用可变部分替换字符串?

它仅适用于预设号码与str_replace

str_replace(array(
    '\\1', 
    '\\2', 
    '\\3', 
    '\\4' 
), array(
    '$matches[1]', 
    '$matches[2]', 
    '$matches[3]', 
    '$matches[4]' 
), $string); 
+2

取看看['preg_repalce()'](http://php.net/manual/en/function.preg-replace.php) – Rizier123

+0

为什么不能以动态的方式创建第一个参数,根据长度第二个参数? – arkascha

回答

1

使用正则表达式preg_replace

代码:

<?php 

$str = '\\2 string \\123 gogog \\123 sda \\342 \\3525 wqe \\234'; 
echo preg_replace('~(\\\\)(\d+)~', '$matches[$2]', $str); 

输出:

$matches[2] string $matches[123] gogog $matches[123] sda $matches[342] $matches[3525] wqe $matches[234]