doufei9805
2017-03-28 11:18
浏览 110
已采纳

preg_match在文本中获取url

I have a test in which users will be having taggings so I need the url href from the text Like i have a text

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

Can anyone help me out as I am unable to do so I am failed in making regex

图片转代码服务由CSDN问答提供 功能建议

我有一个测试,其中用户将有标记,所以我需要文本中的url href像我有一个 text

  Hello World&lt; a class =“red”contenteditable =“false”href =“http://domainname.com/demo/forums/profile/test.name  “&gt;测试&lt; / a&gt;&amp; nbsp;这会产生问题
 //我需要来自url 
 
 $ text = $ post_data-&gt;讨论的test.name; 
 $ name = preg_match_all  ?('#\ bhttps:// [^ \ S()&LT;&GT;] +(?:\([\ W \ d] + \)|([^ [:PUNCT:] \ S] | /)  )#',$ text,$ match); 
 
 print_r($ name); 
   
 
 

任何人都可以帮助我,因为我无法这样做 我制作正则表达式 失败了

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongyu1125 2017-03-28 11:28
    已采纳

    You can check for the anchor tag, that way you'll always get the url (maybe your string contains separate URLs).

    $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
    
    点赞 打赏 评论
  • douqi5079 2017-03-28 11:33

    This should do what you need:

    $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"
      }
    }
    

    Here's an example of it working - https://eval.in/762641

    点赞 打赏 评论

相关推荐 更多相似问题