我正在寻找 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/