Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove tags except mail format container tags

It's difficult to describe my problem by words, I will try by giving an example:

str = '<p>lorem ipsum <[email protected]> donor sit <br></p>';

I need to remove all tags except <[email protected]>

How can we do in javascript and also PHP?

My PHP solution :

class test {
    public function keepMailAddresses($text){
       $callBack = array($this,'_keepMailAddresses');
       return preg_replace_callback('/(<)([^0-9][a-zA-Z0-9_]*([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4})(>)/i', $callBack, $text);        
    }

    private function _keepMailAddresses($matches){
       return '&lt;'.$matches[2].'&gt;';
    }

}

$obj = new test();
echo $obj->keepMailAddresses('<p>lorem ipsum <[email protected]> donor sit <br></p>');
like image 892
Umut KIRGÖZ Avatar asked Nov 03 '22 16:11

Umut KIRGÖZ


2 Answers

ok my solution is little bit weird, but will do the trick :D

$pagecode = '<p>lorem ipsum <[email protected]> donor <[email protected]> sit <[email protected]><br></p>';

// this will check if it's a real email but you don't need it
/*$allowed = preg_match_all("/\<+([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})+\>/i", $pagecode, $matches);*/

$allowed = preg_match_all("/\<([_a-z0-9-\.]+)@([_a-z0-9-\.]+)\>/i", $pagecode, $matches);

$allowed = implode(" ", $matches[0]);
$output = strip_tags($pagecode, $allowed);
echo htmlentities($output);
like image 200
Ghassan Elias Avatar answered Nov 09 '22 12:11

Ghassan Elias


use below in headers section

$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

and put like this

str = '<p>lorem ipsum "<[email protected]>" donor sit <br></p>';
like image 38
Taj Avatar answered Nov 09 '22 12:11

Taj