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]"

 Answers

81

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

Wednesday, March 31, 2021
 
Camsoft
answered 7 Months ago
36

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
 
Bharanikumar
answered 7 Months ago
50

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:

$mail->ClearAllRecipients();

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
 
Classified
answered 5 Months ago
62

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
 
Shobit
answered 5 Months ago
52

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: http://sourceforge.net/projects/simplehtmldom/

Saturday, June 26, 2021
 
Corsair
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 :