php中preg_replace匹配问题

查看:99
本文介绍了php中preg_replace匹配问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

在某个字符串的指定位置增加字符串:

$str = preg_replace('/(.{15})(.*)/is','\1_\2',‘{cmspath}/licai/caijin’);

echo $str;  //这里在字符串15的位置增加了'_'

输出:{cmspath}/licai_/caijin

但如果我需要增加1
写成如下:

$str = preg_replace('/(.{15})(.*)/is','\11\2',‘{cmspath}/licai/caijin’);


输出就不对了啊 ,请问怎样在\1 后面增加1呢? 

解决方案

When working with a replacement pattern where a backreference is immediately followed by another number (i.e.: placing a literal number immediately after a matched pattern), you cannot use the familiar \1 notation for your backreference. \11, for example, would confuse preg_replace() since it does not know whether you want the \1 backreference followed by a literal 1, or the \11 backreference followed by nothing. In this case the solution is to use ${1}1. This creates an isolated $1 backreference, leaving the 1 as a literal.

当在替换模式下工作并且后向引用后面紧跟着需要是另外一个数字(比如:在一个匹配模式后紧接着增加一个原文数字), 不能使用\1这样的语法来描述后向引用。比如, \11将会使preg_replace() 不能理解你希望的是一个\1后向引用紧跟一个原文1,还是 一个\11后向引用后面不跟任何东西。 这种情况下解决方案是使用${1}1。 这创建了一个独立的$1后向引用, 一个独立的原文1。

http://php.net/manual/en/func...

这篇关于php中preg_replace匹配问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆