PHP preg_replace所有实例匹配

时间:2016-05-25 15:28:12

标签: php xml preg-replace

我需要从一些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[] = '$1$2$3xxxxxxxxxxxxxxxx$5';
$replace[] = '$1$2$3xxxxxxxxxxxxxxxx$5';
$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”电子邮件和手机?

1 个答案:

答案 0 :(得分:2)

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

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