PHP:如何替换文本,但仅限于某些标识符之间?

In PHP I need help with replacing certain content in a file that is between certain identifiers.

For example :

abcde
-BEGIN-
   bcdef
-END-
cdefg
-BEGIN-
   doo wah diddy
-END-
defgh

Let's assume I need to replace the 'd' character with a 'z', but ONLY between the -BEGIN- to-END- sections. The result would then be :

abcde
-BEGIN-
   bczef
-END-
cdefg
-BEGIN-
   zoo wah zizzy
-END-
defgh

I tried preg_match_all to succesfully identify the -BEGIN- to -END- sections with:

$text = file_get_contents($file);
preg_match_all('#-BEGIN-.*?-END-#s', $text, $matches);

but can't figure out how to replace something inside these matches and return the whole text including the right replacements.

Any ideas?

Preg_replace() should do the trick.

This searches the blocks inside -BEGIN- and -END- then replaces all occurences of the d character with z (hence the preg_replace() function in the 3rd line).

$str = preg_replace_callback(
    '~(?<=(?<=
|^)-BEGIN-
).*?(?=
-END-)~s',
    create_function('$m','return preg_replace("~d~s","z",$m[0]);'),
    $str
);

EDIT 1: Changed the m flag to s in both Regex rules.


EDIT 2: If you want to make sure here's a better version of the Regex (all possible newline characters taken into account - Windows, Unix etc.).
    '~(?<=
        (?<=
||
|^)   -BEGIN- 
 |
        (?<=
||
|^)   -BEGIN-  |
        (?<=
||
|^)   -BEGIN- 

    )
    .*?
    (?=
        
      -END-   (?=
||
|$) |
              -END-   (?=
||
|$) |
        
    -END-   (?=
||
|$)
    )~xs',