如何从字符串中提取具有特定关键字的链接锚文本

问题描述:

I want to extract the url of all links in a string with certain anchor text.

I saw a previously post on doing this in javascript - can anyone help me do this in PHP?

javascript regex to extract anchor text and URL from anchor tags

我想用某些锚文本提取字符串中所有链接的url。 p>

我在javascript中看过一篇关于这样做的帖子 - 任何人都可以帮助我在PHP中这样做吗? p>

javascript正则表达式从锚标签中提取锚文本和URL p> div>

If you're parsing HTML to extract href attribute values from anchor tags, use an HTML/DOM Parser (definitely don't use regex).

PHP Simple HTML DOM Parser

PHP XML DOM

preg_match_all('#<a\s+href\s*=\s*"([^"]+)"[^>]*>([^<]+)</a>#i', $subject, $matches, PREG_SET_ORDER);

foreach ($matches as $match) {
    echo $match[0]; // <a ... href="url" ...>text</a>
    echo $match[1]; // url
    echo $match[2]; // text
}

This is how I'd do it with regex. There may be more efficient ways but this should be the simplest one.

EDIT: Noticed that you wanted to match all URLs, therefore changed to preg_match_all

preg_match_all