PHP preg_replace里面的文本块

I have some text, like this for example:

$text="<body><div><p>Some test text.</p></div><p>Some test text.</p></body>";

And I have an array of regular expressions:

$regexes = array(
  0 => '/<div>.*<\/div>/',
  1 => '/<p>.*<\/p>/')
;

I need apply each regex in rotation to source $text and when make some replaces in found blocks.

For example:

$result = $text;
foreach ($regexes as $reg) {
  preg_match($reg, $result, $matches);
  $result = $matches[0];
}

return "<p>Some test text.</p>"

How can I replace word "text" to word "new" but only in first part of the $text? The elements (regular expressions) of an array $regexes may be in any quantity and order.

Result should be like this: "<body><div><p>Some new text.</p></div><p>Some test text.</p></body>"

The best thing here would be to split your sections up; I'd imagine this example will be applied to a larger block and unfortunately it's hard to be generic in replacement algorithms - each format will chance how you're best to develop it.

In this case I'm assuming you're splitting based on <div> elements. So we could do:

$elements = explode('</div>',$text);

// in this case your required block is at position [0]

$elements[0]=apply_regex_algorithm($elements[0]);

$text = implode('</div>',$elements);

As mentioned above, how you split will have to vary based on how your text is input to the method and what your specific replacement requirements are.

For more specific editing of text within set elements (i.e. within a larger HTML structure) check the Symfony2 DOM Crawler.