I'm looking for a PHP regex to check if a string ends with a string that
- starts with a space
- then 15 characters which contain only 0-9 and a-f characters (lower case)
Match:
$myString = "something here 62ffe537a66ddcf"; // space after "here" and then 15 characters
No Matches:
$myString1 = "something here62ffe537a66ddcf"; // space missing before the 6
$myString2 = "something here 62ffe537a66ddc"; // only 15 characters (including the space)
$myString3 = "something here 62ffe537A66ddC"; // contains upper case characters
My attempt. There might be a shorter way?
$myString = "something here 62ffe53766ddcf"; // space after "here" and then 15 characters
if (stringEndsWithId($myString)) {
echo "string ends with id";
}
else {
echo "string does not end with id";
}
function stringEndsWithId($str) {
if (str_starts_with(right($str, 16) , ' ')) {
return preg_match('/[^a-f0-9]/', $str);
}
return false;
}
function right($string, $count) {
return substr($string, strlen($string) - $count, $count);
}
CodePudding user response:
You can use [0-9a-f]
to match any of the 0-9 and a-f chars, followed by {15}
to match exactly 15 of them, followed by $
to match the end of the string.
function stringEndsWithId($str) {
return ( preg_match('/ [0-9a-f]{15}$/', $str) );
}