How to replace specified characters in php regular variables

高洛峰
Release: 2023-03-05 06:42:01
Original
2188 people have browsed it

本文实例讲述了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
Copy after login
$text = "foobar123fooabcbar";
$text = preg_replace("/(?<=bar)123/", "***", $text);
//匹配bar后面的位置 foo***123fooabcbar
Copy after login
$text = "foobar123fooabcbar";
$text = preg_replace("/foo(?!bar)/", "***", $text);
//匹配后面跟的不是bar的位置    foobar123***abcbar
Copy after login
$text = "foobar123fooabcbar";
$text = preg_replace("/(?<!foo)bar/", "***", $text);
//匹配前面不是foo的位置 foobar123fooabc***
Copy after login

希望本文所述对大家的php程序设计有所帮助。

更多php正则替换变量指定字符的方法相关文章请关注PHP中文网!

相关文章:

PHP最常用的正则表达式的详解

php正则过滤html标签、空格、换行符的代码

PHP正则表达式匹配替换与分割功能实例浅析

PHP开发技巧(十二)-常用PHP正则表达式的实例代码详解

Related labels:
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!