且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在php中使用preg_replace_callback()来替换文本模式?

更新时间:2023-02-18 17:04:25

text = ' [#ff0000] RedColor [/#ff0000]'; // < - 仅用一个标记替换的文本


text = preg_replace_callback(' / \\ \\ [(#[AF,AF,0-9] {6})\(。*?)\ [(\ /#[AF,AF,0-9] {6})\] / ',function(


m){
if( /跨度>

hi guys,

i have string like "
 [#ff0000] RedColor
      [#0000ff]BlueColor[/#0000ff]
 [/#ff0000]"
and i want to get the HTML code like "
 <font color="#ff0000"> RedColor
      <font color="#0000ff">BlueColor</font>
 </font>"
 from that string





following php code is perfect work with only one font tag

 $text = '[#ff0000] RedColor [/#ff0000]'; // <- text to replace with only one tag
$text = preg_replace_callback('/\[(#[A-F,a-f,0-9]{6})\](.*?)\[(\/#[A-F,a-f,0-9]{6})\]/', function ($m) {
          if("/".$m[1]==$m[3])
         return '<font color="'.$m[1].'">'.$m[2].'</font>';
}, $text);  // <- this is function that return the html code
echo $text;



Out Put
RedColor

but when using nested font(pattern) unexpected result i get

 $text = '[#ff0000] RedColor
      [#0000ff]BlueColor[/#0000ff]
[/#ff0000]'; // <- text to replace with nested tags
 $text = preg_replace_callback('/\[(#[A-F,a-f,0-9]{6})\](.*?)\[(\/#[A-F,a-f,0-9]{6})\]/', function ($m) {
           if("/".$m[1]==$m[3])
          return '<font color="'.$m[1].'">'.$m[2].'</font>';
 }, $text);  // <- this is function that return the html code
 echo $text;


And i got the output like below
[/#ff0000]
instead
RedColor BlueColor



i have visited the following link : here[^] but no solution i got
thanx.

text = '[#ff0000] RedColor [/#ff0000]'; // <- text to replace with only one tag


text = preg_replace_callback('/\[(#[A-F,a-f,0-9]{6})\](.*?)\[(\/#[A-F,a-f,0-9]{6})\]/', function (


m) { if("/".