2015-11-25 34 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]