Jhay
Jhay

Reputation: 77

Substituting HTML for placeholders in string

Is there a way that I can convert these strings into HTML tags and vice versa?

example:

$str = 'The^ff0000 quick brown^000000 fox jumps over the lazy dog.'

the output must be

The<span style="color:#ff0000;"> quick brown</span> fox jumps over the lazy dog.

something like that and vice versa

Upvotes: 0

Views: 152

Answers (4)

Brett Zamir
Brett Zamir

Reputation: 14345

If you are only talking about a few specific codes, you could use:

$str = "The^ff0000 quick brown^000000 fox jumps over the lazy dog.";
$str = str_replace('^ff0000', '<span style="color:#ff0000;">', $str);
$str = str_replace('^000000', '</span>', $str);

or if you prefer:

$str = "The^ff0000 quick brown^000000 fox jumps over the lazy dog.";
$str = str_replace(array('^ff0000', '^000000'), array('<span style="color:#ff0000;">', '</span>'), $str);

If you wish to allow any number of color codes, you might do:

$str = str_replace('^000000', '</span>', $str);
$str = preg_replace('@\^([a-f\d]{6})@i', '<span style="color:#$1;">', $str);

For a conversion back (if you are not using any other </span>'s), it could be:

$str = str_replace('</span>', '^000000', $str);
$str = preg_replace('@<span style="color:#([a-fA-F\d]{6});">@', '^$1', $str);

Note that this assumes you are typing the <span> exactly as above, without variability in whitespace.

Upvotes: 1

pixelbath
pixelbath

Reputation: 55

Since you have no actual closing tag, and would like ^000000 to represent the span closing tag, I'll expand on Mike's answer below.

$string = "The^ff0000 quick brown^000000 fox jumps over the lazy dog.";

// replace '^000000' first so we don't get false positives in the regex
$new_string = str_replace('^000000', '</span>', $string);

$new_string = preg_replace('/\^([0-9a-fA-F]+)\b/i', '<span style="color: #$1;">', $new_string);

Upvotes: 0

ka_lin
ka_lin

Reputation: 9432

This is a good example in which you should implement a Decorator patern (ex: make a static method and process the string using explode for instance and append the spans)

Upvotes: 0

Mike Brant
Mike Brant

Reputation: 71384

Sure it is a simple string replace if the ^(non-000000) value always represents an opening span tag with the hex value being the color style and a ^000000 always means a closing span tag.

Upvotes: 0

Related Questions