Asked  7 Months ago    Answers:  5   Viewed   34 times

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



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);


PHP manual entry:

Credit where credit is due: email regex taken from preg_match manpage, and URL regex taken from:

Wednesday, March 31, 2021
answered 7 Months ago

You need to place the n in double quotes.
Inside single quotes it is treated as 2 characters '' followed by 'n'

You need:

$str = str_replace("n", '', $str);

A better alternative is to use PHP_EOL as:

$str = str_replace(PHP_EOL, '', $str);
Wednesday, March 31, 2021
answered 7 Months ago

There are two problems here:

  • You are not removing the address from the mail, so when you add a second one, the first one is still there and both will see the other address.
  • You are using a header redirect in your loop without terminating your script. This can cause code after the redirect to run, but there is no guarantee for how much and how long.

The first problem you can solve by clearing the recipients at the end of the loop:


As for the second problem, you should not redirect anywhere inside the loop and when you redirect after all messages have been sent, you should exit your scipt using exit; so that nothing gets executed after that.

Saturday, May 29, 2021
answered 5 Months ago

You're using it wrong:

 mail($to, $subject, $body, $from, $headers)

The mail() function does not have a $from parameter. You ought to throw it into $headers as well.

Saturday, May 29, 2021
answered 5 Months ago

To manipulate HTML it is generally a good idea to use a DOM aware tool instead of plain text manipulation tools (think for example what will happen if you enounter variants like <br/>, <br /> with more than one space, or even <br> or <BR/>, which altough illegal are sometimes used). See for example here:

Saturday, June 26, 2021
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :