Cómo comprobar si una cadena comienza con una cadena especificada? [duplicar]


Esta pregunta ya tiene una respuesta aquí:

Estoy tratando de comprobar si una cadena comienza con http. ¿Cómo puedo hacer esta comprobación?

$string1 = 'google.com';
$string2 = 'http://www.google.com';
 336
php
Author: Mridang Agarwalla, 2010-05-07

6 answers

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

Si usted está tratando de asegurarse de que no es otro protocolo. Usaría http:// en su lugar, ya que https también coincidiría, y otras cosas como http-protocol.com.

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

Y en general:

substr($string, 0, strlen($query)) === $query
 584
Author: Kendall Hopkins,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-02 21:23:50

Use strpos():

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

Recuerda los tres signos iguales (===). No funcionará correctamente si solo usa dos. Esto se debe a que strpos() volverá false si la aguja no se encuentra en el pajar.

 451
Author: awgy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-04 07:14:05

También Existe la strncmp() función y strncasecmp() función que es perfecto para esta situación:

if (strncmp($string_n, "http", 4) === 0)

En general:

if (strncmp($string_n, $prefix, strlen($prefix)) === 0)

La ventaja sobre el enfoque substr() es que strncmp() solo hace lo que se necesita hacer, sin crear una cadena temporal.

 56
Author: Sid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-24 19:21:11

Puede usar una expresión regular simple (versión actualizada de user viriathus ya que eregi está obsoleta)

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

O si desea una búsqueda insensible a mayúsculas y minúsculas

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

Las expresiones regulares permiten realizar tareas más complejas

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

En cuanto al rendimiento, no necesita crear una nueva cadena (a diferencia de substr) ni analizar toda la cadena si no comienza con lo que desea. Usted tendrá una penalización de rendimiento aunque la 1a vez que utilice la expresión regular (es necesario crear / compilar).

Esta extensión mantiene una caché global por hilo de compilado regular expresiones (hasta 4096). http://www.php.net/manual/en/intro.pcre.php

 33
Author: user276648,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-06 08:30:47

Puede comprobar si su cadena comienza con http o https utilizando la pequeña función de abajo.

function has_prefix($string, $prefix) {
   return ((substr($string, 0, strlen($prefix)) == $prefix) ? true : false);
}

$url   = 'http://www.google.com';
echo 'the url ' . (has_prefix($url, 'http://')  ? 'does' : 'does not') . ' start with http://';
echo 'the url ' . (has_prefix($url, 'https://') ? 'does' : 'does not') . ' start with https://';
 3
Author: Jake,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-02 19:19:13

También funciona:

if (eregi("^http:", $url)) {
 echo "OK";
}
 -6
Author: viriathus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-07 23:07:18