PHP – String – Obtener valor entre dos strings
Función que devuelve un string el cual esta delimitado por un string inicial y otro de final. La comparación se realiza sin importar las mayúsculas o minúsculas.
Devuelve null si no existen los deliminatodores o string vació si los delimitadores están juntos.
/**
* Class HelperString
*/
abstract class HelperString
{
/**
* Devuelve el texto delimitado entre otros dos textos.
* Devuelve null si lo encuentra.
* '' => No hay caracteres entre los delimitadores
*
* @param $txt
* @param $str_ini
* @param $str_fin
*
* @return string
*/
public static function getBetween($txt, $str_ini, $str_fin)
{
$ret = null;
if (stripos($txt, $str_ini) !== false) {
$pi = stripos($txt, $str_ini) + strlen($str_ini);
$lon = stripos($txt, $str_fin) - $pi;
$ret = substr($txt, $pi, $lon);
if (false === $ret) {
return null;
}
}
return $ret;
}
}
Ejemplos:
$a = HelperString::getBetween("abcdefghijklm", "d", "j");
/* $a = (string:5) efghi */
$a = HelperString::getBetween("abcdefghijklm", "def", "l");
/* $a = (string:5) ghijk */
$a = HelperString::getBetween("abcdefghijklm", "djk", "hi");
/* $a = (string:0) */
