How to replace characters regularly in php

藏色散人
Release: 2023-03-07 19:22:01
Original
2572 people have browsed it

php正则替换字符的方法:首先创建一个PHP示例文件;然后通过“preg_replace("/($str)/","$1",$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);
?>
Copy after login

方法二:

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

方法三:

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

三种方法都返回同样结果.. 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***
Copy after login

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!

Related labels:
php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!