krez krez - 8 months ago 51
PHP Question

preg_match_all and preg_replace in php

I have a large xml file (about 2mb) and need to replace all checkboxes and radio with my additional string =>



<input type="checkbox" />

replace with

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

the code is:

$file = 'style.xml';
$c = file_get_contents($file);
preg_match_all("#<input.*type=\"(checkbox|radio)\".+? />#i", $c, $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);

it works, but sometimes replaced with more than one "I" tag


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

my regex is wrong? or something else?
how to make replacement only once for string?

screenshot here


There's no need to iterate over matches. You can just do it all with a single preg_replace.

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

It matches any checkbox or radio input tag, and replaces that match with $0<i></i> where the $0 refers to the entire match.