php正则获取a标签连接
时间: 2023-09-11 17:08:09 浏览: 40
可以使用正则表达式来匹配 HTML 中的 `<a>` 标签,并获取其中的链接。
以下是一个用 PHP 实现的例子:
```php
$html = '<a href="http://www.example.com">Example</a>
<a href="http://www.google.com">Google</a>';
$pattern = '/<a\s+href=("|\')(.*?)\1/';
preg_match_all($pattern, $html, $matches);
foreach ($matches[2] as $url) {
echo $url . "\n";
}
```
输出结果为:
```
http://www.example.com
http://www.google.com
```
这里的正则表达式是 `/<a\s+href=("|\')(.*?)\1/`,其中:
- `<a\s+href=` 匹配 `<a>` 标签和 `href` 属性,之间可以有任意多个空格;
- `("|\')` 匹配 `href` 属性值的引号,可以是双引号或单引号;
- `(.*?)` 匹配 `href` 属性值,使用非贪婪模式;
- `\1` 匹配和引号相同的字符,这里使用了捕获组来记录引号的类型。
相关问题
正则表达式获取a标签
可以使用以下正则表达式来获取a标签:
```python
import re
html = '<a href="https://www.example.com">Example</a>'
pattern = r'<a.*?href="(.*?)".*?>(.*?)</a>'
match = re.search(pattern, html)
if match:
url = match.group(1)
text = match.group(2)
print(url, text)
```
输出:
```
https://www.example.com Example
```
js正则表达式获取a标签
可以使用正则表达式来获取a标签,具体的正则表达式如下所示:
```javascript
/<a[^>]*href=['"]([^'"]+)['"][^>]*>(.*?)<\/a>/gi
```
其中,`[^>]*`表示匹配除了`>`以外的任意字符,`[^'"]+`表示匹配除了单引号和双引号以外的任意字符,`.*?`表示匹配任意字符,但是尽可能少地匹配。
下面是一个示例代码:
```javascript
const html = '<a href="https://www.baidu.com">百度</a><a href="https://www.google.com">谷歌</a>';
const regex = /<a[^>]*href=['"]([^'"]+)['"][^>]*>(.*?)<\/a>/gi;
let match;
while ((match = regex.exec(html)) !== null) {
console.log(match[1], match[2]);
}
```
输出结果为:
```
https://www.baidu.com 百度
https://www.google.com 谷歌
```