[英]How to extract link anchor text with a certain keyword from a string
I want to extract the url of all links in a string with certain anchor text. 我想提取具有特定锚文本的字符串中所有链接的URL。
I saw a previously post on doing this in javascript - can anyone help me do this in PHP? 我以前看到过用javascript进行此操作的帖子-有人可以在PHP中帮助我吗?
javascript regex to extract anchor text and URL from anchor tags javascript正则表达式从锚标记中提取锚文本和URL
If you're parsing HTML to extract href attribute values from anchor tags, use an HTML/DOM Parser (definitely don't use regex). 如果要解析HTML以从锚标记中提取href属性值,请使用HTML / 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 编辑:注意,您想匹配所有URL,因此更改为preg_match_all
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.