2017-03-28 38 views
0

我有哪些用户将其引用的Tagging测试,所以我需要从文本链接的href像我有一个文本preg_math获取文本中的网址

Hello World <a class="red" contenteditable="false" href="http://domainname.com/demo/forums/profile/test.name">Test </a>&nbsp;this is creating a problem 
//I need test.name from the url 

$text = $post_data->discussion; 
        $name = preg_match_all('#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#', $text, $match); 

        print_r($name); 

谁能帮助我,因为我无法这样做我没有做出正则表达式

+0

你必须使用正则表达式,或者您可以使用HTML解析库? –

+0

这个问题迄今为止在SO上单独回答了多少次? 56390574903次? – arkascha

+0

@arkascha从来没有问过这个问题,为什么你把这件事归咎于我? –

回答

1

你可以检查锚标记,这样你总是会得到的URL(也许你的字符串包含单独的网址)。

$str = 'Hello World <a class="red" contenteditable="false" href="http://domainname.com/demo/forums/profile/test.name">Test </a>&nbsp;this is creating a problem'; 

preg_match_all("/<a.*?href\s*=\s*['\"](.*?)['\"]/", $str, $res, PREG_SET_ORDER); 

foreach($res as $key => $val) { 
    echo $val[1]; 
} 
// http://domainname.com/demo/forums/profile/test.name 
+0

你摇滚感谢很多兄弟 –

0

这应该做你需要的东西:

$regex = '/(?<=href="http)s?:\/\/[\w\.\/]+?\K(\w+\.\w+)(?=">)/'; 
$string = 'Hello World <a class="red" contenteditable="false" href="http://domainname.com/demo/forums/profile/test.name">Test </a>'; 
preg_match_all($regex, $string, $matches); 
var_dump($matches); 

// Outputs 
array(2) { 
    [0]=> 
    array(1) { 
    [0]=> 
    string(9) "test.name" 
    } 
    [1]=> 
    array(1) { 
    [0]=> 
    string(9) "test.name" 
    } 
} 

下面是它的工作的例子 - https://eval.in/762641