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!

4

1 回答 1

1

您没有将替换的值存储在任何地方。此外,如果您在循环外使用替换,它可能会影响模式的所有出现。我认为这会有所帮助:

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>';

}
于 2012-08-29T10:21:18.003 回答