preg_replace replacing with array

Posted by Scott on Stack Overflow See other posts from Stack Overflow or by Scott
Published on 2010-06-12T07:17:01Z Indexed on 2010/06/12 7:22 UTC
Read the original article Hit count: 145

Filed under:
|
|
|

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>

© Stack Overflow or respective owner

Related posts about php

Related posts about regex