使用preg_match检测网址?在字符串中没有http://

时间:2010-05-04 01:29:09

标签: php regex url preg-match

我想知道如何在preg_match中检查一个字符串被分解为一个数组,看它是否以www开头。我已经有一个检查http://www

function isValidURL($url)
{
return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
}

$stringToArray = explode(" ",$_POST['text']);

  foreach($stringToArray as $key=>$val){
  $urlvalid = isValidURL($val);
  if($urlvalid){
  $_SESSION["messages"][] = "NO URLS ALLOWED!";
  header("Location: http://www.domain.com/post/id/".$_POST['postID']);
     exit();
     }
     }

谢谢! 斯蒂芬

5 个答案:

答案 0 :(得分:12)

你想要这样的东西:

%^((https?://)|(www\.))([a-z0-9-].?)+(:[0-9]+)?(/.*)?$%i

这是使用|在开头匹配http://www。我将分隔符更改为%以避免与|

发生冲突

答案 1 :(得分:9)

Daring Fireball的John Gruber发布了一个非常全面的正则表达式,可用于所有类型的URL。你可以在这里找到它:

http://daringfireball.net/2010/07/improved_regex_for_matching_urls

答案 2 :(得分:0)

我首先爆炸了字符串,因为网址可能是它的一半,例如hello how are you www.google.com

分解字符串并使用foreach语句。

例如:

$string = "hello how are you www.google.com";
$string = explode(" ", $string);
foreach ($string as $word){
  if ( (strpos($word, "http://") === 0) || (strpos($word, "www.") === 0) ){
  // Code you want to excute if string is a link
  }
}

请注意,您必须使用===运算符,因为strpos可以返回,将返回0,该false似乎是{{1}}。

答案 3 :(得分:0)

我在下面使用它可以让你在字符串中的任何地方检测网址。对于我的特定应用程序,它是一个打击垃圾邮件的联系表单,因此不允许使用任何URL。效果很好。

资源链接:https://css-tricks.com/snippets/php/find-urls-in-text-make-links/

我的实施;

<?php
// Validate message
if(isset($_POST['message']) && $_POST['message'] == 'Include your order number here if relevant...') {
$messageError = "Required";
} else {
$message = test_input($_POST["message"]);
}
if (strlen($message) > 1000) {
$messageError = "1000 chars max";
}
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
if (preg_match($reg_exUrl, $message)) {
$messageError = "Url's not allowed";
}

// Validate data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

答案 4 :(得分:-2)

试试implode($myarray, '').strstr("www.")==0。这会将您的数组内存为一个字符串,然后检查www.是否位于字符串的开头(索引0)。