php - 正则表达式 PHP,将所有链接与特定文本匹配

标签 php regex pattern-matching html-parsing

我正在寻找 PHP 中的正则表达式,它将 anchor 与上面的特定文本相匹配。例如,我想获得带有文本 mylink 的 anchor ,例如:

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

所以它应该匹配所有 anchor ,但前提是它们包含特定文本所以它应该匹配这些字符串:

<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。

另外这个不应该匹配:"mylink is string" 因为它不是 anchor 。

有人有什么想法吗?

谢谢花岗岩

最佳答案

改用解析器:

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 - 正则表达式 PHP,将所有链接与特定文本匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1661179/

相关文章:

php - WordPress 永久链接在 godaddy 中显示 "You should update your web.config now."

php - 将数据库值存储到变量中

php - 如何在没有原始 fla 文件的情况下制作 swf 链接?

java - 如何使用正则表达式忽略电话号码上的国家/地区代码(带或不带+)

bash - 为什么这个模式匹配 `ab` ,而不是 `ba` ?

php - 使用 PDO 不会插入任何内容

php - 获取字符串的特定部分

javascript - 如何用 RegEx 找到的变量名替换 RegEx?

Scala - 数组上的模式匹配不会对丢失的情况发出警告

pandas - 如何在 pandas.MultiIndex 中找到部分字符串匹配