2016-11-02 110 views
0

我有一個大的XML文件(大約2MB),並且需要與我的額外字符串=><i></i>preg_match_all和preg_replace函數在PHP

例如更換所有複選框和單選

<input type="checkbox" /> 

更換

<input type="checkbox" /><i></i> 

代碼是:

$file = 'style.xml'; 
$c = file_get_contents($file); 
preg_match_all("#<input.*type=\"(checkbox|radio)\".+? />#i", $c, $m); 
if($m) 
{ 
     for($i = 0; $i < count($m[0]); $i++) 
     { 
      /*$search = trim($m[0][$i]); 
      $replace = "$search<i></i>";*/ 
      $c = preg_replace("#" . preg_quote($m[0][$i], "#") . "#i", $m[0][$i] . '<i></i>', $c); 

     } 
} 
    if($fp = @fopen('new-style.xml', 'w')) 
    { 
     @flock($fp, 2); 
     @fputs($fp, $c); 
     @flock($fp, 3); 
     @fclose($fp); 
    } 

它的工作原理,但有時不止一個「我」標籤

例如

<input type="checkbox" /><i></i><i></i><i></i><i></i> 
<input type="radio" /><i></i><i></i><i></i> 

我正則表達式是錯誤的更換?或者是其他東西? 如何讓字符串只替換一次?這裏 image

+1

使用xml解析器。 –

+0

其中一些複選框/收音機輸入是否存在多次? – RST

+0

你可能想考慮[DOMDocument](http://php.net/manual/en/class.domdocument.php)。 – PHPglue

回答

0

截圖有沒有需要遍歷匹配。你可以用一個preg_replace來完成。

preg_replace("#<input.*type=\"(?:checkbox|radio)\".*? />#i", "$0<i></i>", $c);

它任何複選框或單選輸入標籤相匹配,並替換匹配$0<i></i>其中$0指的是整個的匹配。

+0

謝謝凱森! =) – krez