ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-07-22 03:41:02  阅读:169  来源: 互联网

标签:php regex html-parsing pattern-matching


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

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

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

<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”因为它不是锚.

有人有什么想法吗?

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: 
<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,regex,html-parsing,pattern-matching
来源: https://codeday.me/bug/20190722/1498836.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有