PHP preg_replace 所有实例匹配

PHP preg_replace all instance matches

我需要从一些 xml 的日志中清除一些数据,我需要知道如何使 preg_replace 替换所有出现的正则表达式匹配项。

xml 看起来像这样。

<contactData>                 
<id>29194</id>                 
<firstName>Michael</firstName>                 
<lastName>Smith</lastName>                 
<address1>1600 Pennsylvania Ave</address1>                 
<address2></address2>                 
<city>Washington</city>                 
<state>DC</state>                 
<postalCode>20500</postalCode>                 
<country>US</country>                 
<phone>3012013021</phone>                 
<email>michael@potus.gov</email>                 
</contactData>             
<contactData>                 
<id>29195</id>                 
<firstName>Shelly</firstName>                 
<lastName>McPherson</lastName>                 
<address1>2411 Georgia Ave</address1>                 
<address2></address2>                 
<city>Silver Spring</city>                 
<state>MD</state>                 
<postalCode>20902-5412</postalCode>                 
<country>US</country>                 
<phone>3012031302</phone>                 
<email>shelly@example.com</email>
</contactData>

当我运行这个就这个xml。

$regex = $replace = array();
$regex[] = '/(<contactData>)(.*)(<email>)(.*)(<\/email>)/is';
$regex[] = '/(<contactData>)(.*)(<phone>)(.*)(<\/phone>)/is';
$replace[] = 'xxxxxxxxxxxxxxxx';
$replace[] = 'xxxxxxxxxxxxxxxx';
$text = preg_replace($regex, $replace, $text);

我明白了。

<contactData>                 
<id>29194</id>                 
<firstName>Michael</firstName>                 
<lastName>Smith</lastName>                 
<address1>1600 Pennsylvania Ave</address1>                 
<address2></address2>                 
<city>Washington</city>                 
<state>DC</state>                 
<postalCode>20500</postalCode>                 
<country>US</country>                 
<phone>3012013021</phone>                 
<email>michael@potus.gov</email>                 
</contactData>             
<contactData>                 
<id>29195</id>                 
<firstName>Shelly</firstName>                 
<lastName>McPherson</lastName>                 
<address1>2411 Georgia Ave</address1>                 
<address2></address2>                 
<city>Silver Spring</city>                 
<state>MD</state>                 
<postalCode>20902-5412</postalCode>                 
<country>US</country>                 
<phone>xxxxxxxxxxxxxxxx</phone>                 
<email>xxxxxxxxxxxxxxxx</email>
</contactData>

如何用它替换其他 "contactData" 电子邮件和 phone?

使用任何 XML 解析器来执行此操作更为正确。例如简单XML

// Your XML does not inlude root element. 
// If real does, remove `root`from the next line
$xml = simplexml_load_string('<root>' . $text . '</root>'); 
for($i = 0; $i < count($xml->contactData); $i++) {
    unset($xml->contactData[$i]->email);
    unset($xml->contactData[$i]->phone);
}

echo $xml->saveXML();