php 正则匹配所有链接,正则表达式PHP,匹配具有特定文本的所有链接

我在PHP中寻找一个正则表达式,它将锚点与其上的特定文本相匹配.例如,我想获得带有文本mylink的锚:

mylink

所以它应该匹配所有锚点,但只有它们包含特定文本所以它应匹配这些字符串:

mylink

blabla mylink

mylink bla bla

bla bla mylink bla bla

但不是这个:

bla bla bla bla

因为这个不包含单词mylink.

另外这个不应该匹配:“mylink is string”因为它不是锚.

有人有什么想法吗?

Thanx Granit

解决方法:

尝试使用解析器:

require_once "simple_html_dom.php";

$data = 'Hi, I am looking for a regular expression in PHP which would match the anchor with a

specific text on it. E.g I would like to get anchors with text mylink like:

mylink

So it should match all anchors but only if they contain specific text So it should match t

hese string:

mylink

blabla mylink

mylink bla bla

bla bla mylink bla bla

but not this one:

bla bla bla bla Because this one does not contain word mylink.

Also this one should not match: "mylink is string" because it is not an anchor.

Anybody any Idea? Thanx Granit';

$html = str_get_html($data);

foreach($html->find('a') as $element) {

if(strpos($element->innertext, 'mylink') === false) {

echo 'Ignored: ' . $element->innertext . "\n";

} else {

echo 'Matched: ' . $element->innertext . "\n";

}

}

产生输出:

Matched: mylink

Matched: mylink

Matched: blabla mylink

Matched: mylink bla bla

Matched: bla bla mylink bla bla

Ignored: bla bla bla bla

标签:php,regex,html-parsing,pattern-matching

来源: https://codeday.me/bug/20190722/1498836.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值