0

i am having troubles getting my preg_replace to work for a certain string. This is an example of how my original stream looks like:

"This is just a {simple | huge | fast} test to validate {my | your | their} regex"

What i want to do is: I want to replace the parts in between the "{ }" with one (the first one) of the words standing in between. For example:

"This is just a simple test to validate my regex"

So basically what i am currently doing is:

foreach ($zeilen as $key => $value) {

    preg_match_all('/\{(.*?)\}/', $value[15], $arr1);

    foreach($arr1[1] as $key2 => $arrValue){
        preg_match_all('/(.*?)\|/', $arrValue, $arr2);
    }

    preg_replace('/\{(.*?)\}/', 'test', $value[15]);

    echo '<tr>';
    echo '<td>'. $value[15] . '</td>';
    echo '</tr>';

    }

I am using a foreach loop there because there a different lines with the exact same pattern i want to get replaced. I am pretty sure there is a better way to do this, maybe someone can even suggest one to me. My problem here is, that preg_replace is not working at all. The $value[15] is getting echoed out exactly as it was before with the words between { }. No "test" is being displayed. I am not very good at regex!

Thanks a lot to anyone helping!

1 Answer 1

1

You are not storing the replaced values anywhere. Also, if you use replace outside the loop, it might affect all occurances of the pattern. I think this will help:

foreach ($zeilen as $key => $value) {

preg_match_all('/\{(.*?)\}/', $value[15], $arr1);

foreach($arr1[1] as $key2 => $arrValue){
    preg_match('/(.*?)\|/', $arrValue, $arr2);
    $value[15]=str_replace($arr1[0][$key2], $arr2[1], $value[15]);
}

echo '<tr>';
echo '<td>'. $value[15] . '</td>';
echo '</tr>';

}
Sign up to request clarification or add additional context in comments.

Comments

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.