PHP 从 <a> 标签中提取链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6365701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:08:51  来源:igfitidea点击:

PHP extract link from <a> tag

phpstringhyperlinkextracthref

提问by 5et

Possible Duplicate:
PHP String Manipulation: Extract hrefs

可能的重复:
PHP 字符串操作:提取 hrefs

I am using php and have string with content =

我正在使用 php 并且有包含内容的字符串 =

<a href="www.something.com">Click here</a>

<a href="www.something.com">Click here</a>

I need to get rid of everything except "www.something.com" I assume this can be done with regular expressions. Any help is appreciated! Thank you

我需要摆脱除“www.something.com”之外的所有内容,我认为这可以用正则表达式来完成。任何帮助表示赞赏!谢谢

回答by mfonda

This is very easy to do using SimpleXML:

使用 SimpleXML 很容易做到这一点:

$a = new SimpleXMLElement('<a href="www.something.com">Click here</a>');
echo $a['href']; // will echo www.something.com

回答by Tails

Give this a whirl:

试一试:

$link = '<a href="www.something.com">Click here</a>';
preg_match_all('/<a[^>]+href=([\'"])(?<href>.+?)[^>]*>/i', $link, $result);

if (!empty($result)) {
    # Found a link.
    echo $result['href'][0];
}

Result: www.something.com

结果: www.something.com

Updated: Now requires the quoting style to match, addressing the comment below.

更新:现在需要引用样式匹配,解决下面的评论。

回答by anubhava

I would suggest following code for this:

为此,我建议使用以下代码:

$str = '<a href="www.something.com">Click here</a>';
preg_match('/href=(["\'])([^]*)/i', $str, $m);
echo $m[2] . "\n";

OUTPUT

输出

www.something.com

This will take care of both single quote 'and double quote "in the href link.

这将处理href 链接中的单引号'和双引号"

回答by John Poulin

Assuming that is ALWAYSthe format of the variable, below should do the trick. If the content may not be a link, this won't work. Essentially it looks for data enclosed within two quotations.

假设这总是变量的格式,下面应该可以解决问题。如果内容可能不是链接,这将不起作用。本质上,它查找包含在两个引号内的数据。

<?php

$string = '<a href="www.something.com">Click here</a>';

$pattern = '/"[a-zA-Z0-9.\/\-\?\&]*"/';

preg_match($pattern, $string, $matches);
print_r($matches);
?>

回答by hakre

As probably you didn't meant your question that easy, but this does exactly what you're asking for:

可能您的问题并不是那么简单,但这正是您所要求的:

$link = '<a href="www.something.com">Click here</a>';
$href = substr($link, 9, -16);

$hrefis:

$href是:

string(17) "www.something.com"

As a regular expression it can be expressed it as this is:

作为正则表达式,它可以表示为:

$href = preg_match('(^<a href="([^"]*)">Click here</a>$)', $link, $matches) ? $matches[1] : die('Invalid input data.');

Is this helpful?

这有帮助吗?