regexpcre

Regexp : catching all letters and numbers before a specific string


I would like to catch, in order to replace, all letters and numbers placed before a specific string in one preg_replace.

Example : a_dress.mail-123@aol.fr Result : a_aaaaa.aaaa-aaa@aol.fr

I tried (([a-z]*[^\.\-\_]*)|\d*[^\.\-\_]*)(?=(@(?:[\w-]+\.)+[\w-]{2,4})) but it only gets the last matching

Matching with current regexp


Solution

  • You can use

    preg_replace('/[a-zA-Z0-9](?=[^\s@]*@)/', 'a', $text)
    preg_replace('/[^\W_](?=[^\s@]*@)/', 'a', $text)
    

    See the regex demo.

    Details