我有一個大的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
使用xml解析器。 –
其中一些複選框/收音機輸入是否存在多次? – RST
你可能想考慮[DOMDocument](http://php.net/manual/en/class.domdocument.php)。 – PHPglue