Search code examples
phpregexreplacesanitization

Remove letters and spaces which immediately follow the first two letters in a string


I'm trying to replace all the letters and spaces after the first two, using PHP's preg_replace(). Here is my failed attempt at doing so:

echo preg_replace('/^[a-zA-Z]{2}([a-zA-Z ])*.*$/i','','FALL 2012');
//expected output is "FA2012", but it outputs nothing

I'm just trying to replace the part in parentheses ([a-zA-Z ]) .. I'm guessing I'm not doing it right to just replace that part.


Solution

  • You're asking it to replace the entire string. Use a lookbehind to match the first two characters instead.

    echo preg_replace('/(?<=^[a-z]{2})[a-z ]*/i','','FALL 2012');
    

    By the way, the i modifier means it's case insensitive, so you don't need to match both uppercase and lowercase characters.