Search code examples
phpstrpos

PHP string contains two characters then a slash at the beginning


Imagine the following string

/en/pages/title-page  or /es/pages/title-page

How to determine if the string has a slash then two unknown characters (always two) and then another slash. Then once known, can these be extracted from the string.


Solution

  • The following code will have the language in index 1 of the $matches array. Otherwise, if the pattern does not match, the array will be empty.

    $matches = null;
    if (preg_match('/^\/([a-zA-Z]{2})\//', '/en/pages/title-page', $matches) === 1)
        echo $matches[1];
    else
        echo 'No language found';