Search code examples
phpemailhide

Find and replace emails and phone numbers in PHP


I was hoping for a little help on this, as it's confusing me a little... I run a website that allows users to send messages back and forth, but on the inbox i need to hide both emails and phone numbers.

Example: This is how a sample email would look like.

Hi, my phone is +44 5555555 and email is jack@jack.com

I need it to be like this:

Hi, my phone is (phone hidden) and email is (email hidden)

Do you have any ideas ?... I really appreciate it!..


Solution

  • $x = 'Hi, my phone is +44 5555555 and email is jack@jack.com';
    $x = preg_replace('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i','(phone hidden)',$x); // extract email
    $x = preg_replace('/(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?/','(email hidden)',$x); // extract phonenumber
    echo $x; // Hi, my phone is (phone hidden) and email is (email hidden)
    

    kudo's for the phonenumber regex to fatcat