$1",$txt );" method can replace the specified characters in the variable."/> $1",$txt );" method can replace the specified characters in the variable.">

Home  >  Article  >  Backend Development  >  How to replace characters regularly in php

How to replace characters regularly in php

藏色散人
藏色散人Original
2020-11-24 09:25:442582browse

php正则替换字符的方法:首先创建一个PHP示例文件;然后通过“preg_replace("/($str)/","5934cee47c75b184d1e5d1f111b69020$154bdf357c58b8a65c66d7c19c8e4d114",$txt);”方法实现替换变量指定字符即可。

How to replace characters regularly in php

推荐:《PHP视频教程
本教程操作环境:windows7系统、PHP5.6版,该方法适用于所有品牌电脑。

php正则替换字符的方法:

php正则替换变量指定字符的方法,php替换变量字符

本文实例讲述了php正则替换变量指定字符的方法。分享给大家供大家参考。具体如下:

这里介绍三种常用方法.

方法一:

<?php
$str = preg_quote(&#39;(银子)&#39;);
$txt = &#39;我的呢称(银子)&#39;;
echo preg_replace("/($str)/","<span style=&#39;color:#f00;&#39;>$1</span>",$txt);
?>

方法二:

<?php
$str = quotemeta(&#39;(银子)&#39;);
$txt = &#39;我的呢称(银子)&#39;;
echo preg_replace("/($str)/","<span style=&#39;color:#f00;&#39;>$1</span>",$txt);
?>

方法三:

<?php
$str = &#39;(银子)&#39;;
$txt = &#39;我的呢称(银子)&#39;;
echo preg_replace("/(Q$strE)/","<span style=&#39;color:#f00;&#39;>$1</span>",$txt);
?>

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

一些其它关于正则的实例

例子:

$text = "foobar123fooabcbar";
$text = preg_replace("/foo(?=bar)/", "***", $text);
//匹配bar前面的位置 ***bar123fooabcbar
$text = "foobar123fooabcbar";
$text = preg_replace("/(?<=bar)123/", "***", $text);
//匹配bar后面的位置 foo***123fooabcbar
$text = "foobar123fooabcbar";
$text = preg_replace("/foo(?!bar)/", "***", $text);
//匹配后面跟的不是bar的位置    foobar123***abcbar
$text = "foobar123fooabcbar";
$text = preg_replace("/(?<!foo)bar/", "***", $text);
//匹配前面不是foo的位置 foobar123fooabc***

The above is the detailed content of How to replace characters regularly in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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