PHP preg
时间:2023年10月05日
/来源:网络
/编辑:佚名
<?php
$userinfo = "Name: <b>PHP</b> <br> Title: <b>Programming Language</b>";
preg_match_all ("/<b>(.*)<\/b>/U", $userinfo, $pat_array);
print_r($pat_array[0]);
?>
执行结果如下所示:
Array
(
[0] => <b>PHP</b>
[1] => <b>Programming Language</b>
)
查找匹配的HTML标签(贪婪):
<?php
//\\2是一个后向引用的示例. 这会告诉pcre它必须匹配正则表达式中第二个圆括号(这里是([\w]+))
//匹配到的结果. 这里使用两个反斜线是因为这里使用了双引号.
$html = "<b>bold text</b><a href=howdy.html>click me</a>";
preg_match_all("/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER);
foreach ($matches as $val) {
echo "matched: " . $val[0] . "\n";
echo "part 1: " . $val[1] . "\n";
echo "part 2: " . $val[2] . "\n";
echo "part 3: " . $val[3] . "\n";
echo "part 4: " . $val[4] . "\n\n";
}
?>
执行结果如下所示:
matched: <b>bold text</b>
part 1: <b>
part 2: b
part 3: bold text
part 4: </b>
matched: <a href=howdy.html>click me</a>
part 1: <a href=howdy.html>
part 2: a
part 3: click me
part 4: </a>
$userinfo = "Name: <b>PHP</b> <br> Title: <b>Programming Language</b>";
preg_match_all ("/<b>(.*)<\/b>/U", $userinfo, $pat_array);
print_r($pat_array[0]);
?>
执行结果如下所示:
Array
(
[0] => <b>PHP</b>
[1] => <b>Programming Language</b>
)
查找匹配的HTML标签(贪婪):
<?php
//\\2是一个后向引用的示例. 这会告诉pcre它必须匹配正则表达式中第二个圆括号(这里是([\w]+))
//匹配到的结果. 这里使用两个反斜线是因为这里使用了双引号.
$html = "<b>bold text</b><a href=howdy.html>click me</a>";
preg_match_all("/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER);
foreach ($matches as $val) {
echo "matched: " . $val[0] . "\n";
echo "part 1: " . $val[1] . "\n";
echo "part 2: " . $val[2] . "\n";
echo "part 3: " . $val[3] . "\n";
echo "part 4: " . $val[4] . "\n\n";
}
?>
执行结果如下所示:
matched: <b>bold text</b>
part 1: <b>
part 2: b
part 3: bold text
part 4: </b>
matched: <a href=howdy.html>click me</a>
part 1: <a href=howdy.html>
part 2: a
part 3: click me
part 4: </a>
新闻资讯 更多
- 【建站知识】查询nginx日志状态码大于400的请求并打印整行04-03
- 【建站知识】Python中的logger和handler到底是个什么?04-03
- 【建站知识】python3拉勾网爬虫之(您操作太频繁,请稍后访问)04-03
- 【建站知识】xpath 获取meta里的keywords及description的方法04-03
- 【建站知识】python向上取整以50为界04-03
- 【建站知识】scrapy xpath遇见乱码解决04-03
- 【建站知识】scrapy爬取后中文乱码,解决word转为html 时cp1252编码问题04-03
- 【建站知识】scrapy采集—爬取中文乱码,gb2312转为utf-804-03