正则表达式PHP,将所有链接与特定文本匹配 [英] Regex PHP, Match all links with specific text

查看:100
本文介绍了正则表达式PHP,将所有链接与特定文本匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

<a href="blabla" ... >mylink</a>

因此它应该与所有锚匹配,但前提是它们包含特定文本,因此应与以下字符串匹配:

So it should match all anchors but only if they contain specific text So it should match these strings:

<a href="blabla" ... >mylink</a>

<a href="blabla" ... >blabla mylink</a>

<a href="blabla" ... >mylink bla bla</a>

<a href="blabla" ... >bla bla mylink bla bla</a>

但不是这个:

<a href="blabla" ... >bla bla bla bla</a>

因为这个不包含单词mylink.

Because this one does not contain word mylink.

这也不应该匹配:"mylink is string",因为它不是锚点.

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

有人知道吗?

感谢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: 
<a href="blabla" ... >mylink</a>

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

<a href="blabla" ... >mylink</a>

<a href="blabla" ... >blabla mylink</a>

<a href="blabla" ... >mylink bla bla</a>

<a href="blabla" ... >bla bla mylink bla bla</a>

but not this one:

<a href="blabla" ... >bla bla bla bla</a> 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

从以下位置下载simple_html_dom.php: http://simplehtmldom.sourceforge.net/

这篇关于正则表达式PHP,将所有链接与特定文本匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆