从字符串中过滤网址并匹配域名

时间:2011-11-25 06:08:11

标签: php regex

我必须匹配并过滤来自字符串的url并匹配域名。例如,字符串是

  

$ s =“是否有人有一个有效的preg_match脚本用于检查和   验证正确的URL提交到html表单   http:/stackoverflow.com/questions/ask验证http:/google.com“;

查找字符串包含任何网址,网址与http//stackoverflow.com

匹配

样本输出如

http:/stackoverflow.com/questions/ask 

1 个答案:

答案 0 :(得分:0)

你也可以在php中使用filter_var()函数。     

    $s="Does anyone have a working preg_match script for checking and validating a correct url submission into a html form http://stackoverflow.com/questions/ask/ validating http://google.com";

$words = explode(' ',$s );
$urls = array();
foreach($words as $word){

if(!(filter_var($word, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED) === FALSE))
        {
         /*** try to the filter the URL ***/
        $urls[] = $word;
        }


}
echo "<pre>";
print_r($urls);
echo "</pre>";

?>