0

I'm not sure if this can be done with preg_replace, but this is what I have so far

$string='
<div class="row">
  <section> [1] </section>
  <section> [2] </section>
  <section> [5] </section>
</div>';


function searchArray($myarray, $id) {
    foreach ($myarray as $item) {
        if ($item[$id] == $id)
            return $item['name'];
    }
    return false;
}

So I need to run $string through preg_replace where each var between [] will correspond to an actual id stored in multidimensional array. This is where function searchArray() comes in. Basically runs string, replace [] with actual id's and print name of the field. All this needs to happen when I submit form in one pass.

1 Answer 1

1

How about something like this as an alternative to *preg_replace*...

$arr = array('apple', 'pear', 'bananna', 'orange', 'grapefruit', 'pineapple');
$string='
<div class="row">
  <section> [1] </section>
  <section> [2] </section>
  <section> [5] </section>
</div>';

foreach($arr as $key => $value){
    $string = str_replace($key, $value, $string);
}

UPDATE

$arr = array(
    array('id'=>1, 'name'=>'matthew'),
    array('id'=>2, 'name'=>'william'),
    array('id'=>3, 'name'=>'john'),
    array('id'=>4, 'name'=>'george'),
    array('id'=>5, 'name'=>'henry'),
    array('id'=>6, 'name'=>'jason')
);
$string='
<div class="row">
  <section> [1] </section>
  <section> [2] </section>
  <section> [4] </section>
    <section> [1] </section>
</div>';
foreach($arr as $key => $subArr){
    $string = str_replace("[".$subArr['id']."]", $subArr['name'], $string);
}
Sign up to request clarification or add additional context in comments.

3 Comments

That's not going to work. It's multidimensional array, and each [] needs to match actual id, than to be replaced with corresponding name value
So what ID's are you looking to replace? If it's multi-dimensional then it will be in the form [][] ??
Okay, I've updated my answer with some more code which (if I now understand what you were aiming to do) should be what you're looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.