简体   繁体   中英

PHP: replace all occurrences of “[CODE]…[/CODE]” in a string

I've got a string like this:

Here is my code sample, its not too great:

[CODE]
<?php
    echo "Some testing...";
?>
[/CODE]

I hope you enjoy.

Now I want to replace ALL occurrences of [CODE] ... [/CODE] with the return value of highlight_string($content_of_CODE) . The [CODE]..[/CODE]-pair may appear multiple times in the string.

How can I solve this without using eval?

Thank you for your help!

假设[CODE]块没有嵌套, preg_replace_callback()是一个完美的候选者。

preg_replace_callback('/\[CODE\](.*?)\[/CODE\]/', 'highlight_string');

使用这个正则表达式:

(?s)\[CODE\].*?\[/CODE\]

content_of_CODE = reg_replace('/ [!\\ s +!] | [\\ s * / * CODE] /','',$ content_of_CODE);

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