PHP extract link from tag [duplicate]

2019-01-14 04:17发布

Possible Duplicate:
PHP String Manipulation: Extract hrefs

I am using php and have string with content =

<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

5条回答
Fickle 薄情
2楼-- · 2019-01-14 04:37

Assuming that is ALWAYS the 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);
?>
查看更多
不美不萌又怎样
3楼-- · 2019-01-14 04:39

Give this a whirl:

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

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

Result: www.something.com

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

查看更多
Rolldiameter
4楼-- · 2019-01-14 04:51

This is very easy to do using SimpleXML:

$a = new SimpleXMLElement('<a href="www.something.com">Click here</a>');
echo $a['href']; // will echo www.something.com
查看更多
ら.Afraid
5楼-- · 2019-01-14 04:58

I would suggest following code for this:

$str = '<a href="www.something.com">Click here</a>';
preg_match('/href=(["\'])([^\1]*)\1/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.

查看更多
叛逆
6楼-- · 2019-01-14 04:58

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);

$href is:

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?

查看更多
登录 后发表回答