现在我们大家所说的正则表达式基本上是指兼容Perl风格的正则表达式。POSIX风格的正则表达式基本上没人使用了,所以从PHP5.3起,已经不推荐使用了,可能到PHP的下一个版本就会把相关的函数删除。
关于正则表达式,因为太复杂,所以以后想专看一本正则的书,所以只介绍兼容Perl风格的正则表达式的一些函数。
1. 定界符
定界符表示正则表达式的开始和结尾,一般用斜线(/)表示。在PHP中(其它语言暂时没有测试过),它也可以用其它的非数字字母的字符来代替。如/\d+/和#\d+#的表示同一个正则表达式\d+。同时,也可以用小括号对,中括号对,大括号对做为定界符,如[\d+]。
2. 函数
匹配函数:preg_match(); 以及preg_match_all();
替换函数:preg_replace();
拆分函数:preg_split();
过滤函数:preg_grep();
示例代码:
复制代码 代码如下:
$a = aaaaaaa 15
bbbbbbb 16
TEXT;
$ret = preg_match(/(\w+) (\d+)/, $a, $match);
// $ret : 1
// $match : array(aaaaaaa 15′, aaaaaaa, 15′)
$ret = preg_match_all(/(\w+) (\d+)/, $a, $match);
// $ret : 2
// $match : array(
// array(aaaaaaa 15′, bbbbbbb 16′),
// array(bbbbbbb, bbbbbbb),
// array(15′, 16′),
// )
$ret = preg_match_all(/(\w+) (\d+)/, $a, $match, PREG_SET_ORDER);
// $ret : 2
// $match : array(
// array(aaaaaaa 15′, bbbbbbb, 15′),
// array(bbbbbbb 16′, bbbbbbb, 16′),
// )
$b = preg_replace(/(\w+) (\d+)/, \1, \2′, $a);
// $b : aaaaaaa, 15
// bbbbbbb, 16′
$c = preg_split(/\s/, $a);
// $c : array(aaaaaaa, 15′, bbbbbbb, 16′)
$files = array(aa.txt, bb.xls, cc.txt);
$txtFiles = preg_grep(/.*\.txt/, $files);
// $txtFiles : array(aa.txt, cc.txt)
参考资料:
PHP程序设计,2003,第四章 字符串,正则表达式

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!