我仍然有点难以理解您到底在追求什么。不过,这是我最好的尝试。
<?php
$string = '<a href="https://www.facebook.com/l.php?u=https%3A%2F%2Fthelittleboxoffice.com%2Fheritagehotel%2Fevent%2Fview%2F22847&h=RAQFYdp-K&s=1" target="_blank" rel="nofollow" onmouseover="LinkshimAsyncLink.swap(this, "https:\\/\\/thelittleboxoffice.com\\/heritagehotel\\/event\\/view\\/22847");" onclick="LinkshimAsyncLink.swap(this, "https:\\/\\/www.facebook.com\\/l.php?u=https\\u00253A\\u00252F\\u00252Fthelittleboxoffice.com\\u00252Fheritagehotel\\u00252Fevent\\u00252Fview\\u00252F22847&h=RAQFYdp-K&s=1");"><div id="u_0_p">Find Tickets</div></a><';
if (preg_match('~(<a href(.*?)Find Tickets(.*?)</a>)~i', $string, $matches)) {
print "<PRE><FONT COLOR=ORANGE>"; print_r($matches); print "</FONT></PRE>";
}
我在这里真正要做的就是寻找一个以<a href 开头的字符串,然后是一个字符串,直到它到达Find Tickets,可能还有更多的东西,直到它到达结尾的</a>。
这是一个非常通用的正则表达式,但如果您正在寻找更具体的东西,您可以以此为基础。
编辑:
好的,所以从您的评论来看,我想我对您正在寻找的东西有了更好的了解。这是一个更新的正则表达式,它将提取链接文本与 Find Tickets 匹配的链接的 URL。
<?php
$string = '
<a href="http://www.google.com" style="color: blue;">Google</a>
<a href="https://www.facebook.com/l.php?u=https%3A%2F%2Fthelittleboxoffice.com%2Fheritagehotel%2Fevent%2Fview%2F22847&h=RAQFYdp-K&s=1" target="_blank" rel="nofollow" onmouseover="LinkshimAsyncLink.swap(this, "https:\\/\\/thelittleboxoffice.com\\/heritagehotel\\/event\\/view\\/22847");" onclick="LinkshimAsyncLink.swap(this, "https:\\/\\/www.facebook.com\\/l.php?u=https\\u00253A\\u00252F\\u00252Fthelittleboxoffice.com\\u00252Fheritagehotel\\u00252Fevent\\u00252Fview\\u00252F22847&h=RAQFYdp-K&s=1");"><div id="u_0_p">Find Tickets</div></a>
<a href="http://www.yahoo.com">Yahoo</a>';
if (preg_match('~<a href="(.*?)"(?:.*?)(?:(?=Find Tickets))(?:.*?)</a>~i', $string, $matches)) {
print "<PRE><FONT COLOR=ORANGE>"; print_r($matches); print "</FONT></PRE>";
}
这就是这个表达式的作用:
-
(.*?) - 这是实际捕获 URL 并将其存储到 $matches[1] 中的部分。
-
(?:.*?) - 这允许任何东西在 URL 之后直到它到达下一部分(前瞻)。由于我们实际上并不需要这些信息,?: 告诉 REGEX 不要记住它找到的内容。
-
(?:(?=Find Tickets)) - 这是一个积极的前瞻,意思是为了进行匹配,文本 Find Tickets 必须 出现在下一个。与上一项一样,我们使用?: 告诉它实际上不需要记住匹配项。如果文本匹配诸如“不查找门票”之类的内容 - (?=>Find Tickets<),您可能可以在文本周围包含 html 括号以进一步锁定它。
-
(?:.*?) - 最后一部分与前面的相同,只匹配到结束 </a> 标记之前的任何内容。
从上面的$string,这会给你这个:
Array
(
[0] => <a href="https://www.facebook.com/l.php?u=https%3A%2F%2Fthelittleboxoffice.com%2Fheritagehotel%2Fevent%2Fview%2F22847&h=RAQFYdp-K&s=1" target="_blank" rel="nofollow" onmouseover="LinkshimAsyncLink.swap(this, "https:\/\/thelittleboxoffice.com\/heritagehotel\/event\/view\/22847");" onclick="LinkshimAsyncLink.swap(this, "https:\/\/www.facebook.com\/l.php?u=https\u00253A\u00252F\u00252Fthelittleboxoffice.com\u00252Fheritagehotel\u00252Fevent\u00252Fview\u00252F22847&h=RAQFYdp-K&s=1");"><div id="u_0_p">Find Tickets</div></a>
[1] => https://www.facebook.com/l.php?u=https%3A%2F%2Fthelittleboxoffice.com%2Fheritagehotel%2Fevent%2Fview%2F22847&h=RAQFYdp-K&s=1
)
$matches[1] 包含 URL。
希望它能为您实现目标!