简体   繁体   中英

How to use preg_replace backreference instead of preg_match and preg_replace?

I am trying to use shortcode function on content after the body tag.

preg_match("/<body[^>]*>(.*?)<\/body>/is", $html, $matches);
$html= preg_replace("/<body[^>]*>(.*?)<\/body>/is",run_shortcodes($matches[1]), $body);
echo $html;

And this works ok but I would like to do this with preg_replace backreference if possible.

I have tried something like this but obviously it is wrong

$html= preg_replace("/<body[^>]*>(.*?)<\/body>/is",run_shortcodes('$1'), $body);

Can someone please show a possible example of using backreference.

Any help is appreciated .

Here's an example:

preg_match("/<body[^>]*>(.*?)<\/body>/is", $html, $matches);
$newBody = run_shortcodes($matches[1]);
echo preg_replace('/(.*<body[^>]*>)(.*)(<\/body>.*)/is', '${1}'.$newBody.'${3}', $html);

You can also try:

$html = preg_replace_callback("/<body[^>]*>(.*?)<\/body>/is", 'run_shortcodes', $subject);
echo $html;

You need to use preg_replace_callback

http://php.net/manual/en/function.preg-replace-callback.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM