I am doing a preg_replace on a string and the replacement contains a count variable that needs to be placed inbetween the pattern. But I am having difficulty doing that as the count is taken as a pattern and not as a count variable. Here is my code.


$count = 0;
$result_stringXa = "<select>
<option value = 'lb1'>ListItem1</option>
<option value = 'lb2'>ListItem2</option>
<option value = 'lb3'>ListItem3</option>
</select>"

if (preg_match('<select>', $result_stringXa))
{
$count++;
}
$string = $result_stringXa;
$pattern = '<select>';
$replacement = '< select \'lb\$count\'>';
echo preg_replace($pattern, $replacement, $string);
}

Try to change if to while and remove the first }.

<?
	$count = 0;
$result_stringXa = "<select>
<option value = 'lb1'>ListItem1</option>
<option value = 'lb2'>ListItem2</option>
<option value = 'lb3'>ListItem3</option>
</select>";

if(preg_match('<select>', $result_stringXa))
{
	$count++;
}
$string = $result_stringXa;
$pattern = '/<select>/';
$replacement = "<select 'lb$count'>";
echo preg_replace($pattern, $replacement, $string);

?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.