krez krez - 1 month ago 8
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 =>

<i></i>


example

<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);
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);
}


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

example

<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
image

Answer

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.

Comments