views:

19

answers:

1

What I want to do is replace the "[replace]" in input string with the corresponding vaule in the replace array. The total number of values will change but there will always be the same number in the replace array as in input string. I have tried doing this with preg_replace and preg_replace_callback but I can't get the pattern right for [replace], I also tried using vsprintf but the % in <table width="100%"> was messing it up. All help is greatly appreciated!

Replace Array:

$array = array('value 1','value 2','value 3');

Input String

$string = '
<table width="100%">
<tr>
<td>Name:</td>
<td>[replace]</td>
</tr>
<tr>
<td>Date:</td>
<td>[replace]</td>
</tr>
<tr>
<td>Info:</td>
<td>[replace]</td>
</tr>
</table>
';

Desired Result

<table width="100%">
<tr>
<td>Name:</td>
<td>value 1</td>
</tr>
<tr>
<td>Date:</td>
<td>value 2</td>
</tr>
<tr>
<td>Info:</td>
<td>value 3</td>
</tr>
</table>
+2  A: 

You escape table's % with %%:

$string = <<<EOD
<table width="100%%">
<tr>
<td>Name:</td>
<td>%s</td>
</tr>
<tr>
<td>Date:</td>
<td>%s</td>
</tr>
<tr>
<td>Info:</td>
<td>%s</td>
</tr>
</table>
EOD;

$array = array('value 1','value 2','value 3');

echo vsprintf($string, $array);

ouput:

<table width="100%">
<tr>
<td>Name:</td>
<td>value 1</td>
</tr>
<tr>
<td>Date:</td>
<td>value 2</td>
</tr>
<tr>
<td>Info:</td>
<td>value 3</td>
</tr>
</table>
Artefacto
Ah, Thanks I couldn't find the escape information anywhere and I never had to do it before, do you know of a function that does this?
Scott
str_replace( '%', '%%', $string); works, thanks!
Scott