PHP正则表达式应用汇总
本内容整理了PHP中一些经典且实用的正则表达式案例,供读者参考学习。
对于开发者而言,正则表达式是一项极为重要的工具,能够实现句子、单词或其他格式字符串的查找、匹配与替换。下文列举了若干高效的PHP正则用法,供有需要的朋友查阅。
1. 验证域名:用于检测一个字符串是否符合有效域名的格式规范。
<?php
$url = "https://www.baidu.com";
if (preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?\/?/i', $url)) {
echo "Your url is ok.";
} else {
echo "Wrong url.";
}
2. 单词高亮:实现从指定字符串中定位并突出显示某个特定单词的功能。
该功能可在字符串中精准匹配目标单词并进行高亮处理,对于优化搜索结果展示非常有效。
<?php
$text = "Sample sentence from KomunitasWeb, regex has become popular in web programming. Now we learn regex. According to wikipedia, Regular expressions (abbreviated as regex or
regexp, with plural forms regexes, regexps, or regexen) are written in a formal language that can be interpreted by a regular expression processor";
$text = preg_replace("/(regex)/i", '1', $text);
echo $text;
function get_the_title(){
return 'Save the search.php file and open style.css. Append the following line to it: ';
}
$s = 'and php';
$title = get_the_title();
$keys= explode(" ",$s);
$title = preg_replace('/('.implode('|', $keys) .')/iu',
'\0',
$title);
echo $title;
3. 提取HTML图片:用于从HTML文档中获取所有图片链接。
若需批量获取网页上的所有图片资源,此段代码十分适用,可轻松构建图片下载爬虫。
<?php
$images = array();
$data = file_get_contents('https://www.baidu.com');
preg_match_all('/(img|src)=("|\')[^"\'>]+/i', $data, $media);
unset($data);
$data=preg_replace('/(img|src)("|\'|="|=\')(.*)/i',"$3",$media[0]);
foreach($data as $url)
{
$info = pathinfo($url);
if (isset($info['extension']))
{
if (($info['extension'] == 'jpg') ||
($info['extension'] == 'jpeg') ||
($info['extension'] == 'gif') ||
($info['extension'] == 'png'))
array_push($images, $url);
}
}
var_dump($images);
4. 匹配XML或HTML标签:通过简单函数即可识别特定的XML或HTML标签结构。
该函数接收两个参数:第一个为待匹配的标签名称,第二个为包含XML或HTML内容的变量。其功能强大且简洁。
<?php
function get_tag( $tag, $xml ) {
$tag = preg_quote($tag);
output($tag);
preg_match_all('/<'.$tag.'[^>]*>(.*?)<\/'.$tag.'>./',
$xml,
$matches,
PREG_PATTERN_ORDER
);
return $matches[1];
}
$xml = 'bbbbbcccbbaaddd
';
$tag = 'a';
$return = get_tag($tag, $xml);
var_dump($return);
/*
array(2) {
[0]=>
array(3) {
[0]=>
string(11) "bbb<"
[1]=>
string(10) "aa<"
[2]=>
string(11) "ddd<"
}
[1]=>
array(3) {
[0]=>
string(3) "bbb"
[1]=>
string(2) "aa"
[2]=>
string(3) "ddd"
}
}
array(3) {
[0]=>
string(3) "bbb"
[1]=>
string(2) "aa"
[2]=>
string(3) "ddd"
}
*/
此外,推荐两款便捷的正则表达式在线测试工具供辅助使用:
JavaScript正则表达式在线测试工具: 点击使用
希望上述内容能对各位的PHP编程工作提供切实帮助。