PHP和正则表达式结合使用可以实现强大的数据采集功能。下面是一些常用的技巧:
$pattern = '/<title>(.*?)<\/title>/';
$html = file_get_contents('http://example.com');
preg_match($pattern, $html, $matches);
$title = $matches[1];
$pattern = '/<a href="(.*?)">(.*?)<\/a>/';
$html = file_get_contents('http://example.com');
preg_match_all($pattern, $html, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$url = $match[1];
$text = $match[2];
// 处理采集到的数据项
}
$pattern = '/<script.*?<\/script>/';
$html = file_get_contents('http://example.com');
$clean_html = preg_replace($pattern, '', $html);
$pattern = '/<title>(.*?)<\/title>/i';
$html = file_get_contents('http://example.com');
preg_match($pattern, $html, $matches);
$title = $matches[1];
$pattern = '/<a href="(.*?)">(.*?)<\/a>/';
$html = file_get_contents('http://example.com');
preg_match($pattern, $html, $matches);
$url = $matches[1];
$text = $matches[2];
$pattern = '/<a href="(\w+)">(.*?)<\/a>/';
$html = file_get_contents('http://example.com');
preg_match($pattern, $html, $matches);
$url = $matches[1];
$text = $matches[2];
这些技巧可以帮助你在PHP中使用正则表达式进行数据采集。根据实际需求,你可以灵活运用这些技巧来处理各种不同的数据采集任务。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站