数据采集是一项常见的任务,而使用PHP和正则表达式可以轻松解决许多数据采集难题。下面是一些常见的数据采集问题和使用PHP和正则表达式解决方案的示例。
$html = file_get_contents('http://example.com');
$pattern = '/<h1>(.*?)<\/h1>/i';
preg_match_all($pattern, $html, $matches);
// 提取的标题存储在$matches数组中
$titles = $matches[1];
$file = file_get_contents('data.txt');
$pattern = '/\d{3}-\d{3}-\d{4}/';
preg_match_all($pattern, $file, $matches);
// 提取的电话号码存储在$matches数组中
$phoneNumbers = $matches[0];
$html = file_get_contents('table.html');
$dom = new DOMDocument();
$dom->loadHTML($html);
$table = $dom->getElementsByTagName('table')[0];
$rows = $table->getElementsByTagName('tr');
$data = [];
foreach ($rows as $row) {
$cells = $row->getElementsByTagName('td');
$rowData = [];
foreach ($cells as $cell) {
$rowData[] = $cell->nodeValue;
}
$data[] = $rowData;
}
// 提取的数据存储在$data数组中
以上是一些使用PHP和正则表达式解决数据采集难题的示例。根据具体的需求,可能需要根据实际情况调整正则表达式和代码逻辑。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站