0

I need to remove all email and phone number from string in PHP. Can someone help me on this?

Kara
  • 5,996
  • 16
  • 49
  • 56
mahendura
  • 21
  • 1
  • 2

1 Answers1

3

This is just for a start up not a complete answer. You need to read more about regular expressions and its usage.

remove email addresses :

$pattern = "/[^@\s]*@[^@\s]*\.[^@\s]*/";
$replacement = "[removed]";
preg_replace($pattern, $replacement, $string);

Reference

For phone numbers :

$text = preg_replace('/\+?[0-9][0-9()-\s+]{4,20}[0-9]/', '[removed]', $text);

this looks for:

a plus symbol (optional), followed by a number, followed by between 4-20 numbers, brackets, dashes or spaces, followed by a number

and replaces with the string [removed].

Reference

Community
  • 1
  • 1
Zigma
  • 529
  • 5
  • 35
  • that wont match all legit email addresses. ditto for the phone numbers –  May 27 '13 at 09:21
  • yes. I was editing post.to add the same – Zigma May 27 '13 at 09:24
  • + rather than * maybe? – stevemarvell Nov 18 '15 at 14:08
  • 1
    Email removal is working fine but phone number removal is not working. I am getting this error: preg_replace(): Compilation failed: invalid range in character class at offset 16 – ankit suthar Dec 06 '17 at 13:17
  • @ankitsuthar you may need to escape the hyphen by putting a \ in front of it - eg see https://stackoverflow.com/questions/60377374/laravel-preg-replace-compilation-failed-invalid-range-in-character-class – user6122500 Jul 05 '21 at 05:32