PHP正则表达式(Regular Expression)是一种强大的文本处理工具,用于匹配、查找、替换字符串中的特定模式。在PHP中,正则表达式主要通过preg_match
、preg_match_all
、preg_replace
等函数来实现。
preg_match
或preg_match_all
函数来查找字符串中是否包含某个模式。preg_replace
函数来替换字符串中符合某个模式的子串。假设我们要从一个网页中采集内容列表,可以使用以下代码:
<?php
$url = 'http://example.com/list';
$html = file_get_contents($url);
// 假设内容列表的HTML结构如下:
// <ul>
// <li>Item 1</li>
// <li>Item 2</li>
// <li>Item 3</li>
// </ul>
preg_match_all('/<li>(.*?)<\/li>/s', $html, $matches);
$items = $matches[1];
foreach ($items as $item) {
echo $item . "\n";
}
?>
原因:
解决方法:
DOMDocument
)来处理复杂的HTML结构。<?php
$url = 'http://example.com/list';
$html = file_get_contents($url);
$dom = new DOMDocument();
@$dom->loadHTML($html); // 忽略HTML解析错误
$items = $dom->getElementsByTagName('li');
foreach ($items as $item) {
echo $item->nodeValue . "\n";
}
?>
通过以上方法,可以有效地解决PHP正则表达式采集内容列表时遇到的问题。
领取专属 10元无门槛券
手把手带您无忧上云