Search code examples
phparraysregexpreg-replaceplaceholder

Replace multiple identical placeholders in a string using an array of values (one at a time)


What I want to do is replace the "[replace]" in input string with the corresponding value 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.

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>

Solution

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