Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP regex to check if a string ends with a space and 15 other characters

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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);
}

>Solution :

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) );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading