Skip to content

Instantly share code, notes, and snippets.

@twysto
Last active March 31, 2023 10:08
Show Gist options
  • Save twysto/b313af55e1d25e898c593d4207a6333d to your computer and use it in GitHub Desktop.
Save twysto/b313af55e1d25e898c593d4207a6333d to your computer and use it in GitHub Desktop.
PHP: Safe PCRE Regex Match `spreg_match(...)`
<?php
if (! function_exists('spreg_match')) {
function spreg_match(
string $pattern,
string $subject,
array &$matches = null,
int $flags = 0,
int $offset = 0
): ?string {
$return = null;
$subject = substr($subject, $offset);
try {
$res = @preg_match($pattern, $subject, $matches, $flags, $offset);
if (preg_last_error() !== PREG_NO_ERROR) {
throw new \Exception(preg_last_error_msg());
} elseif ($res === 1 && count($matches) > 1) {
$return = array_shift($matches);
}
} catch (\Throwable $e) {
die('Error: ' . $e->getmessage());
}
return $return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment