2016-05-25 10 views
1

いくつかのデータをいくつかのXMLのログからスクラブする必要があり、preg_replaceをどのようにして正規表現マッチのすべてのものに置き換えるかを知る必要があります。PHP 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>[email protected]</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>[email protected]</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>[email protected]</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

この質問と回答を見ていてください:http://stackoverflow.com/questions/10523887/replace-all-occurrences-inside-pattern –

+2

利用のDOMDocumentとDOMXPathを使うことの最大の、ありません正規表現を使用してください。 –

+0

http://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php – AbraCadaver

答えて

2

これを行うには、任意のXMLパーサーを使用する方が適切です。 exampeについては、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(); 
+1

あなたは正しいです。私はXMLリクエストを可能な限り手に入らないようにしたいので、これを避けましたが、潜在的な問題を抱えて正規表現を使用するのは愚かです。 – Halfstop

+2

はい、あなたは正しい判断をしました。がんばろう! – splash58

関連する問題