preg_replace 替换值有子表达式值加数值问题

WBOY
Release: 2016-06-23 13:59:50
Original
1131 people have browsed it

如下面简单的替换:
$ih=100;
$aa='a123b';
$aa=preg_replace('/^(a)123(b)$/i','$1'.$ih.'$2',$aa);
print_r($aa);
怎么结果就是不对,$ih变为字母就正常,数字的话会丢第一位和$1。在$1随便加个字母也正常,不会是我电脑问题吧?


回复讨论(解决方案)

$aa=preg_replace('/^(a)123(b)$/ie','"$1".$ih."$2"',$aa);
Copy after login

preg_replace('/^(a)*(b)$/i','$1'.$ih.'$2',$aa);

$ih=500;$aa='a123b';$aa=preg_replace('/^(a)123(b)$/i','${1}'.$ih.'${2}',$aa);print_r($aa);
Copy after login

'$1'.$ih.'$2'
Copy after login

相当于
'$1'.‘100’.'$2'$1100$2
Copy after login

修改规则 '$1'.$ih.'$2'
实际传递给 preg_replace 的是 ‘$1100$2'
于是 $1 和 $11 就产生了歧义
所以需要人工将其区别开来 ‘${1}100$2'
按你的格式就是 '${1}'.$ih.'$2'
注意:不能使用双引号

都回答的很好,可惜分不多。早知道早点来这问了,郁闷了一整天。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template