Regexp : catching all letters and numbers before a specific string

50 Views Asked by At

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

1

There are 1 best solutions below

0
Wiktor Stribiżew On BEST ANSWER

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.