Php 如何用可变部分替换字符串?
我想将每个Php 如何用可变部分替换字符串?,php,Php,我想将每个\x替换为$matches[x],其中x是一个数字 它仅适用于带有str\u replace的预定义数字: str_replace( array( '\\1', '\\2', '\\3', '\\4' ), array( '$matches[1]', '$matches[2]', '$matches[3]', '$matches[4]' ), $string ); 在中使用正则表达式 代码: 看看为什么不能根据第二个参数
\x
替换为$matches[x]
,其中x是一个数字
它仅适用于带有str\u replace
的预定义数字:
str_replace( array(
'\\1',
'\\2',
'\\3',
'\\4'
), array(
'$matches[1]',
'$matches[2]',
'$matches[3]',
'$matches[4]'
), $string );
在中使用正则表达式 代码:
看看为什么不能根据第二个参数的长度以动态方式创建第一个参数?
<?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]