的任務是找到字符串是否以http://或https://或ftp://URL驗證PHP
$正則表達式=「((HTTPS | FTP)://)? 「;
但的preg_match($正則表達式)無法正常工作。我應該改變什麼?
的任務是找到字符串是否以http://或https://或ftp://URL驗證PHP
$正則表達式=「((HTTPS | FTP)://)? 「;
但的preg_match($正則表達式)無法正常工作。我應該改變什麼?
你需要使用一個分隔符(/)周圍的正則表達式:)
// Protocol's optional
$regex = "/^((https?|ftp)\:\/\/)?/";
// protocol's required
$regex = "/^(https?|ftp)\:\/\//";
if (preg_match($regex, 'http://www.google.com')) {
// ...
}
您需要:preg_match ('#((https?|ftp)://)?#', $url)
的#
定界符刪除需要逃避/
,這是更方便的網址
是否有必要使用正則表達式?
if (strpos($url, 'http://') === 0 ||
strpos($url, 'https://') === 0 ||
strpos($url, 'ftp://') === 0)
{
// do magic
}
羅..正則表達式更加快速和穩定的:) – 2010-01-28 02:35:55
我真的希望你在開玩笑。 – robbo 2010-01-28 02:42:05
不,我不是:http://dreamfall.blogspot.com/2008/02/php-benchmarks-strpos-vs-pregmatchall.html – 2010-01-28 13:08:49
像這樣::人們可以使用字符串函數實現同樣的事情
$search_for = array('http', 'https', 'ftp');
$scheme = parse_url($url, PHP_URL_SCHEME);
if (in_array($scheme, $search_for)) {
// etc.
}
是我所需要的第二正則表達式 – Dan 2010-01-28 12:45:35