Home > php教程 > php手册 > php正则替换中变量的指定字符

php正则替换中变量的指定字符

WBOY
Release: 2016-06-13 09:47:40
Original
960 people have browsed it

下面举了三个实现来介绍在php正则替换中变量的指定字符,有需要学习的机友可参考参考。

三种方法.

1.

 代码如下 复制代码

$str = preg_quote('(银子)');
$txt = '我的呢称(银子)';
echo preg_replace("/($str)/","$1",$txt);
?>

2.

 代码如下 复制代码

$str = quotemeta('(银子)');
$txt = '我的呢称(银子)';
echo preg_replace("/($str)/","$1",$txt);
?>

3.

 代码如下 复制代码
$str = '(银子)';
$txt = '我的呢称(银子)';
echo preg_replace("/(Q$strE)/","$1",$txt);
?>

三种方法都返回同样结果.. PHP中的Perl风格正则与Perl完全一样.连quotemeta也是通用的..


一些其它关于正则的实例

例子:

 代码如下 复制代码

$text  = “foobar123fooabcbar”;

$text = preg_replace(“/foo(?=bar)/”, “***”, $text);

//匹配bar前面的位置 ***bar123fooabcbar

 

 代码如下 复制代码

$text  = “foobar123fooabcbar”;

$text = preg_replace(“/(?

//匹配bar后面的位置  foo***123fooabcbar

 

 代码如下 复制代码

$text  = “foobar123fooabcbar”;

$text = preg_replace(“/foo(?!bar)/”, “***”, $text);

//匹配后面跟的不是bar的位置       foobar123***abcbar

 

 代码如下 复制代码

$text  = “foobar123fooabcbar”;

$text = preg_replace(“/(?

//匹配前面不是foo的位置 foobar123fooabc***

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template