Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove email addresses and links from a string in PHP?

How do I remove all email addresses and links from a string and replace them with "[removed]"

like image 492
JEagle Avatar asked Jul 21 '10 19:07

JEagle


2 Answers

You can use preg_replace to do it.

for emails:

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

for urls:

$pattern = "/[a-zA-Z]*[:\/\/]*[A-Za-z0-9\-_]+\.+[A-Za-z0-9\.\/%&=\?\-_]+/i";
$replacement = "[removed]";
preg_replace($pattern, $replacement, $string);

Resources

PHP manual entry: http://php.net/manual/en/function.preg-replace.php

Credit where credit is due: email regex taken from preg_match manpage, and URL regex taken from: http://www.weberdev.com/get_example-4227.html

like image 153
Josiah Avatar answered Nov 03 '22 12:11

Josiah


Try this:

$patterns = array('<[\w.]+@[\w.]+>', '<\w{3,6}:(?:(?://)|(?:\\\\))[^\s]+>');
$matches = array('[email removed]', '[link removed]');
$newString = preg_replace($patterns, $matches, $stringToBeMatched);

Note: you can pass an array of patterns and matches into preg_replace instead of running it twice.

like image 6
treeface Avatar answered Nov 03 '22 13:11

treeface