how to replace email address from html innertext

2019-08-27 16:04发布

问题:

i have a problem, for replacing email address from html innertext.

i can replace all email address. but i can't replace only specific(innertext of html). please help me..

i have tried with preg_replace('/[A-Z0-9._%+-]+@([A-Z0-9.-]+\.[A-Z]{2,4}|[A-Z0-9.-]+)/iu','[---]',$data)

please help me. thanks...

my input

<div  data="example1@dom.com,example4@dom.com"><a href="example1@dom.com" > example4@dom.com,  <b>example3@dom.com</b>  other text, example7@dom.com, ,<i>example5@dom.com</i></a></div >

expected output:

<div  data="example1@dom.com,example4@dom.com"><a href="example1@dom.com" > [--],  <b>[--]</b>  other text, [--] ,<i>[--]</i></a></div >

live demo

回答1:

Through PCRE verb (*SKIP)(*F).

<[^<>]*>(*SKIP)(*F)|[A-Z0-9._%+-]+@([A-Z0-9.-]+\.[A-Z]{2,4}|[A-Z0-9.-]+)

DEMO

<[^<>]*> matches all the tags and the following PCRE verb (*SKIP)(*F) makes the match to fail completely. Then the regex engine tries to match the pattern which was at the right of | symbol against the remaining string.

$re = "/<[^<>]*>(*SKIP)(*F)|[A-Z0-9._%+-]+@([A-Z0-9.-]+\\.[A-Z]{2,4}|[A-Z0-9.-]+)/mi";
$str = "<div data=\"example1@dom.com,example4@dom.com\"><a href=\"example1@dom.com\" > example4@dom.com, <b>example3@dom.com</b> other text, example7@dom.com, ,<i>example5@dom.com</i></a></div >\n";
$subst = "[---]";
$result = preg_replace($re, $subst, $str);
echo $result;

Output:

<div data="example1@dom.com,example4@dom.com"><a href="example1@dom.com" > [---], <b>[---]</b> other text, [---], ,<i>[---]</i></a></div >


回答2:

[A-Z0-9._%+-]+@([A-Z0-9.-]+\.[A-Z]{2,4}(?![^<]*>)|[A-Z0-9.-]+)(?![^<]*>)

Try this.See demo.

http://regex101.com/r/yR3mM3/6

$re = "/[A-Z0-9._%+-]+@([A-Z0-9.-]+\\.[A-Z]{2,4}(?![^<]*>)|[A-Z0-9.-]+)(?![^<]*>)/mi";
$str = "<div data=\"example1@dom.com,example4@dom.com\"><a href=\"example1@dom.com\" > example4@dom.com, <b>example3@dom.com</b> other text, example7@dom.com, ,<i>example5@dom.com</i></a></div >";
$subst = "[---]";

$result = preg_replace($re, $subst, $str);

Output:<div data="example1@dom.com,example4@dom.com"><a href="example1@dom.com" > [---], <b>[---]</b> other text, [---], ,<i>[---]</i></a></div >