【问题标题】:Match if string is there in anchor tag如果锚标记中存在字符串,则匹配
【发布时间】:2016-01-08 10:32:47
【问题描述】:

我想测试锚标签之间是否有字符串,例如:
这是示例文本<a href=""> this is test string </a>,这是其他锚标记<a href=""> link again </a> 谢谢。

在上面的字符串中,如果锚标签之间有“test”,我想匹配。如何用正则表达式做到这一点。

请帮忙!

谢谢。

【问题讨论】:

标签: php regex match


【解决方案1】:

这是一个你可以使用的函数:

function getTextBetweenTags($string, $tagname) {
    $pattern = "/<$tagname ?.*>(.*)<\/$tagname>/";
    preg_match($pattern, $string, $matches);
    return $matches[1];
}
$str = '<a href=""> this is test string </a>';
$txt = getTextBetweenTags($str, "a");

echo $txt;
// Will return " this is test string ".

【讨论】:

  • 但是字符串可能有很多数据。在一个大字符串中,锚标签很少,我需要在这些锚标签中找到。所以这种情况下它可能不起作用。
  • 感谢 Jeremy 的及时回复.. 这是一个很好的答案.. 但如果我在一个字符串中有多个锚标签,那么我想知道。那也不是全文,只是我需要的一个词。
  • 你真的想匹配“测试”,对不起,我只是一个例子;)
【解决方案2】:

试试下面的代码:

$x='<a href="">This is a test string</a>';

if(preg_match_all('~<a href="">.+test.+</a>~i',$x,$m))
{echo "Match";}
else
{echo "No match";}

【讨论】:

    猜你喜欢
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    相关资源
    最近更新 更多