PHP: Bir dize belirtilen bir dize ile başlar olmadığını nasıl kontrol?

6 Cevap

Ben bir dize http ile başlar olmadığını kontrol etmek için çalışıyorum. Ben bu onay nasıl yapabilirim?

$string1 = 'google.com';
$string2 = 'http://www.google.com';

6 Cevap

substr( $string_n, 0, 4 ) === "http"

Eğer başka bir protokol değil emin olmak için çalışıyoruz. Ben https de maç olur beri, http:// kullanmak yerine, ve bu tür http-protocol.com gibi başka şeyler olurdu.

substr( $string_n, 0, 7 ) === "http://"

Kullan strpos():

if (0 === strpos($string2, 'http')) {
   // It starts with 'http'
}

Üç işaretleri (===) eşittir hatırlıyorum. Yalnızca iki kullanmak eğer düzgün çalışmaz. Iğne samanlıkta bulunamazsa eğer strpos() false dönecektir çünkü bu.

Sen (eregi önerilmiyor gibi kullanıcıdan gelen güncellenmiş sürümü viriathus), basit bir regex kullanabilirsiniz

if (preg_match('#^http#', $url) === 1) {
    // Starts with http (case sensitive).
}

ya da bir harf duyarsız arama isterseniz

if (preg_match('#^http#i', $url) === 1) {
    // Starts with http (case insensitive).
}

Regexes allow to perform more complex tasks

if (preg_match('#^https?://#i', $url) === 1) {
    // Starts with http:// or https:// (case insensitive).
}

Performans açısından, sizin ne istediğiniz ile başlamak değilse (substr ile aksine) yeni bir dize oluşturmak ne de tüm dizeyi ayrıştırmak gerekmez. Eğer regex kullanmak 1st zaman (sen / derlemek oluşturmanız gerekir) olsa bir performans ceza olacaktır.

This extension maintains a global per-thread cache of compiled regular expressions (up to 4096). http://www.php.net/manual/en/intro.pcre.php

Bu durum için mükemmel strncmp () fonksiyonu ve strncasecmp () fonksiyonu da var.

Bu aşağıda gibi çok basit. . .

$Submitted = "http://www.google.com";

//If string start's with http://
if(substr($Submitted, 0, 7) == "http://") {
     $HTTP = "True";
} else { $HTTP = "False"; }


//If string start's with https://
if(substr($Submitted, 0, 8) == "https://") {
     $HTTPS = "True";
} else { $HTTPS = "False";

echo "Url contains http:// | ${HTTP}";//Which would return true or false
echo "Url contains https:// | ${HTTPS}";//Which would return true or false

Daha fazla bilgi için php.net ile substr() işlevi ve if statement bakınız.

Ayrıca işe:

if (eregi("^http:", $url)) {
 echo "OK";
}