本文实例讲述了PHP正则表达式匹配替换与分割功能。分享给大家供大家参考,具体如下:
正则表达式在PHP中的作用主要包括:分割、匹配、查找与替换。
[b]匹配功能[/b]
preg_match_all 全部匹配函数
preg_match_all (string pattern,string subject,array matches[, int flags]);
对结果的排序使 $matches[0] 为全部模式匹配的数组。
用途:截取比较精确的内容,用于采集网页,分析文本等。
[b]替换功能[/b]
preg_replace 正则替换函数
preg_replace(mixed pattern,mixed replacement,mixed subject[, int limit]);
通过正则表达式来替换相关内容。
① 替换内容可以是一个正则也可以是数组;
② 替换内容可以通过修正符 e 来解决替换执行内容。
用途:替换一些比较复杂的内容,也可以将内容进行转换。
[b]分割功能[/b]
preg_split 正则切割
preg_split(string pattern,string subject[, int limit[, int flags]]);
通过正则表达式来切割相关内容,类似 explode 切割函数,但 explode 只能以一种方式进行切割。
[b]实例演示[/b]
匹配功能
以下为引用内容:
<?php
$str="标题:{title}内容:{content}";
$mode="/{(.*)}/U";
preg_match_all($mode,$str,$arr);
print_r($arr);
?>
输出:(在源文件中查看)
以下为引用内容:
Array
(
[0] => Array
(
[0] => {title}
[1] => {content}
)
[1] => Array
(
[0] => title
[1] => content
)
)
[b]PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:[/b]
[b]JavaScript正则表达式在线测试工具:
[/b][url=http://tools.jb51.net/regex/javascript]http://tools.jb51.net/regex/javascript[/url]
[b]正则表达式在线生成工具:
[/b][url=http://tools.jb51.net/regex/create_reg]http://tools.jb51.net/regex/create_reg[/url]
更多关于PHP相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/180.htm]php正则表达式用法总结[/url]》、《[url=http://www.1sucai.cn/Special/623.htm]PHP数组(Array)操作技巧大全[/url]》、《[url=http://www.1sucai.cn/Special/348.htm]PHP基本语法入门教程[/url]》、《[url=http://www.1sucai.cn/Special/357.htm]PHP运算与运算符用法总结[/url]》、《[url=http://www.1sucai.cn/Special/43.htm]php面向对象程序设计入门教程[/url]》、《[url=http://www.1sucai.cn/Special/495.htm]PHP网络编程技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/47.htm]php字符串(string)用法总结[/url]》、《[url=http://www.1sucai.cn/Special/84.htm]php+mysql数据库操作入门教程[/url]》及《[url=http://www.1sucai.cn/Special/231.htm]php常见数据库操作技巧汇总[/url]》
希望本文所述对大家PHP程序设计有所帮助。