Search code examples
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 : [email protected] Result : [email protected]

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

    • [^\W_] / [a-zA-Z0-9] - a letter or digit
    • (?=[^\s@]*@) - immediately to the right, there must be zero or more chars other than whitespaces and @ and then a @ char.