Knowledge Base

¿Qué es esto?

PHP: Saber si un caracter existe en un string. Si existe devuelve su posición

04/05/2015 - 18/12/2018 -  Comentarios - PHP Strings

Podemos averiguar si un substring está contenido en otro, usaríamos la función strpos:

<?php

$mystring = 'abc';

$findme   = 'a';

$pos = strpos($mystring, $findme);

// Nótese el uso de ===. Puesto que == simple no funcionará como se espera

// porque la posición de 'a' está en el 1° (primer) caracter.

if ($pos === false)

{

    echo "The string '$findme' was not found in string '$mystring'";

} else {

    echo "The string '$findme' was found in '$mystring'";

    echo " and exists at position $pos";

}

?>