Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/246.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/docker/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何用可变部分替换字符串?_Php - Fatal编程技术网

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]