URL doğrulama php

4 Cevap php

Görev dize http:// veya https:// ya da ftp:// ile başlarsa bulmak için

$ Regex = "((https | ftp): \? \ / \ /?)";

ama preg_match ($ regex) düzgün çalışmıyor. Ne değiştirmek gerekir?

4 Cevap

Sen RegExp etrafında bir sınırlayıcı (/) kullanmanız gerekir :)

// Protocol's optional
$regex = "/^((https?|ftp)\:\/\/)?/";
// protocol's required
$regex = "/^(https?|ftp)\:\/\//";

if (preg_match($regex, 'http://www.google.com')) {
    // ...
}

http://br.php.net/manual/en/function.preg-match.php

Bu regex kullanmak gerekli midir? Bir dize fonksiyonlarını kullanarak aynı şeyi elde edebiliriz:

if (strpos($url, 'http://')  === 0 ||
    strpos($url, 'https://') === 0 ||
    strpos($url, 'ftp://')   === 0)
{
    // do magic
}

İhtiyacınız: preg_match ('#((https?|ftp)://)?#', $url)

# ayraclar URL'ler için daha uygun olan, / kaçmaya ihtiyacı kaldırmak

Bu gibi:

$search_for = array('http', 'https', 'ftp');
$scheme = parse_url($url, PHP_URL_SCHEME);
if (in_array($scheme, $search_for)) {
    // etc.
}