以下是一个简单的PHP实例,用于采集网址内容。这个例子中,我们将使用PHP的文件函数来读取网页内容,并解析出所需的网址。
| 步骤 | 说明 | 代码 |
|---|---|---|
| 1 | 引入文件函数 | ` |
| 2 | 设置目标网址 | `$url='http://www.example.com';` |
| 3 | 使用file_get_contents()获取网页内容 | `$html=file_get_contents($url);` |
| 4 | 使用preg_match_all()匹配网址 | `$pattern='/http(s)?://([""w-]+"".)+[""w-]+(/[""w-./?%&=]*)?/i';` |
| 5 | 解析网址 | `$matches=array();` |
| 6 | 执行正则表达式匹配 | `preg_match_all($pattern,$html,$matches);` |
| 7 | 输出所有匹配的网址 | `foreach($matches[0]as$match){echo$match.' ';}` |
| 8 | 结束PHP代码 | `?>` |
```php

$url = 'http://www.example.com';
$html = file_get_contents($url);
$pattern = '/http(s)?://([""w-]+"".)+[""w-]+(/[""w- ./?%&=]*)?/i';
$matches = array();
preg_match_all($pattern, $html, $matches);
foreach ($matches[0] as $match) {
echo $match . '
';
}
>
```
在这个例子中,我们首先设置了目标网址`http://www.example.com`。然后,使用`file_get_contents()`函数获取网页内容,并存储在变量`$html`中。接下来,我们定义了一个正则表达式`$pattern`来匹配网址,并使用`preg_match_all()`函数执行匹配。我们遍历匹配结果并输出所有匹配的网址。
请注意,这个例子仅用于演示目的,实际应用中可能需要考虑更多的因素,如错误处理、跨域请求等。







