Home > php教程 > php手册 > body text

PHP中的正则表达式函数preg

WBOY
Release: 2016-06-06 19:53:46
Original
1479 people have browsed it

preg_match(); //用于正则表达式的匹配,且只匹配一次 preg_match_all();//用于正则表达式的匹配,会对所有符合规则的都进行匹配 preg_replace(); //正则表达式替换函数 preg_splite(); //正则分割函数 preg_match ( mode, string subject , arraymatches )

preg_match();     //用于正则表达式的匹配,且只匹配一次

preg_match_all();//用于正则表达式的匹配,会对所有符合规则的都进行匹配

preg_replace();   //正则表达式替换函数

preg_splite();     //正则分割函数


preg_match ( mode, string subject , arraymatches )

其中mode是正则规则,string subject是要匹配的字符串,arraymatches是匹配的结果数组

例子:

<?php $mode='/[89]/';//匹配8或者9
$str="djfkdsjk10903990sjdfdk";
preg_match($mode,$str,$arr);
print_r($arr);
?>
Copy after login

输出:
Array ( [0] => 9 ) 
Copy after login

preg_match_all ( mode, string subject , arraymatches )

该函数和preg_match_all()函数的功能类似,不过该函数会匹配所有符合要求的内容,并将之存放到字符串中。


例子:

<?php $mode='/[89]/';//匹配8或者9
$str="dj33f44k88dsjk10903990sjdfdk";
preg_match_all($mode,$str,$arr);
print_r($arr);
?>
Copy after login

输出:

Array ( [0] => Array ( [0] => 8 [1] => 8 [2] => 9 [3] => 9 [4] => 9 ) ) 
Copy after login

preg_replace ( mixed pattern, mixed replacement,mixed subject [, int limit] )

通过正则表达式来替换相关内容,类似之前学过的str_replace字符串替换,但功能要强于它。


特点:1、替换内容可以是一个正则也可以是数组正则

          2、替换内容可以通过修正符e来解决替换执行内容

用途:替换一些比较复杂的内容上,也可以用于内容的转换上

例子1——数组正则:

<?php $mode=array('/{title}/','/{author}/','/{url}/');
$re=array("code cloud","qianshou","http://codecloud.duapp.com/");
$str="标题:{title}<br>作者:{author}<br>地址:{url}";
echo "<hr>";
if($tag=preg_replace($mode,$re,$str)){
 echo $tag;
}else{
 echo "替换不成功!";
}
?>
Copy after login


输出:

标题:code cloud
作者:qianshou
地址:http://codecloud.duapp.com/
Copy after login

例子2——ubb代码的替换:
<?php $str="欢迎来到我的博客:[url]http://blog.csdn.net/qsyzb[/url]";
$re=preg_replace('/\[url\](.*)\[\/url\]/',"<a href=\"\\1\" target=\"new\">\\1",$str);
echo "<hr>".$re."<hr>";
?>
Copy after login

输出:
<hr>欢迎来到我的博客:<a href="http://blog.csdn.net/qsyzb" target="new">http://blog.csdn.net/qsyzb</a><hr>
Copy after login

preg_split ( string pattern, string subject [, intlimit [, int flags]] )

通过正则表达式来切割相关内容,类似之前学过的explode切割函数,但explode只能按照一种方式切割有局限性。

例子:

<?php $mode='/[,.#]/';
$str='one,two.three#four';
if($tag=preg_split($mode,$str)){
 print_r($tag);
}else{
 echo "替换不成功!";
}
?>
Copy after login

输出:
Array
(
    [0] => one
    [1] => two
    [2] => three
    [3] => four
)
Copy after login


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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template