Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
PHP
 $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
PHP
 $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.
Posted
Updated 9-Jul-15 22:02pm
v3

1 solution

Your text string is wrong in 2nd case. Please try this:

PHP
<?php
    $text = '[#ff0000] RedColor [/#ff0000] [#0000ff]BlueColor[/#0000ff]';// <- 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;
?>



Your text string should be like this :

$text = '[#ff0000] RedColor [/#ff0000] [#0000ff]BlueColor[/#0000ff]';


Tag for RedColor should be closed before starting of BlueColor. Hope it helps :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900