How to replace specified characters in php regular variables
Mar 17, 2017 pm 03:37 PM
php
variable
replace
regular
本文实例讲述了php正则替换变量指定字符的方法。分享给大家供大家参考。具体如下:
这里介绍三种常用方法.
方法一:
<?php $str = preg_quote('(银子)'); $txt = '我的呢称(银子)'; echo preg_replace("/($str)/","<span style='color:#f00;'>$1</span>",$txt); ?>
Copy after login
方法二:
<?php $str = quotemeta('(银子)'); $txt = '我的呢称(银子)'; echo preg_replace("/($str)/","<span style='color:#f00;'>$1</span>",$txt); ?>
Copy after login
方法三:
<?php $str = '(银子)'; $txt = '我的呢称(银子)'; echo preg_replace("/(Q$strE)/","<span style='color:#f00;'>$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中文网!
相关文章:
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

Hot Article
How Long Does It Take To Beat Split Fiction?
3 weeks ago
By DDD
Repo: How To Revive Teammates
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌

Hot tools Tags

Hot Article
How Long Does It Take To Beat Split Fiction?
3 weeks ago
By DDD
Repo: How To Revive Teammates
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian

How To Set Up Visual Studio Code (VS Code) for PHP Development
