Skip to content

Instantly share code, notes, and snippets.

@Erenor
Last active September 28, 2022 08:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Erenor/49845d9d49d27578b8d7216c2086a749 to your computer and use it in GitHub Desktop.
Save Erenor/49845d9d49d27578b8d7216c2086a749 to your computer and use it in GitHub Desktop.
[PHP] Workaround for the absent "ereg()" function, in PHP 7+
//make sure the function is not already there ;-)
if (!function_exists('ereg'))
{
//@see https://stackoverflow.com/questions/6270004/how-can-i-convert-ereg-expressions-to-preg-in-php
//@see http://php.net/manual/en/function.ereg.php
//@see http://php.net/manual/en/function.preg-match.php
function ereg($pattern, $string, $matches = null)
{
//quote delimiters, if already present in the pattern (ereg does not have delimiters)
$pattern = preg_quote($pattern, '~');
//add delimiters to pattern
$pattern = '~' . $pattern . '~';
//check function's third parameter
if (!isset($matches))
{
//there is no matches array
$result = preg_match($pattern, $string);
}
else
{
$result = preg_match($pattern, $string, $matches);
}
//preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.
//ereg() returns the length of the matched string if a match for pattern was found in string, or FALSE if no matches were found or an error occurred.
// If the optional parameter "regs" was not passed or the length of the matched string is 0, this function returns 1.
if ($result === false)
{
//ok
return false;
}
else if ($result === 0)
{
//ereg returns "false", if a match has not been found
return false;
}
else
{
//ereg returns 1 if there was no "matches" array or lentgh of matched string is 0
if (
!isset($matches)
|| (strlen($matches[0]) === 0)
)
{
//no matches array, so we just return "1"
return 1;
}
else
{
//first element in $matches contains matched string
return strlen($matches[0]);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment