user12246451
user12246451

Reputation:

How set font color in php after a character

I have a string selected from database, and I want to change the font color of string after a '<', then back to initial color after '>'. Example: rowselected= abcd<efgh>lmno

How can I change the color of efgh?

I tried with

<?php between ('<', '>', rowselected) echo '<span style="color:red;">' . rowselected . '</span>' ?>

obviusly not work, but i'm searching a solution like this

Upvotes: 0

Views: 383

Answers (2)

Claudio
Claudio

Reputation: 5213

A solution using a regex to get the matches on the string and then replace them:

$str = 'abcd<efgh>lmno';

preg_match_all('/<[\S]*?>/m', $str, $matches, PREG_PATTERN_ORDER);

$replacements = $needles = [];
foreach ($matches[0] as $match) {
    $needles[]      = $match;
    $replacements[] = '<span style="color:red;">' . $match . '</span>';
}

echo str_replace($needles, $replacements, $str);

Result: abcd<span style="color:red;"><efgh></span>lmno

Upvotes: 1

Tamim
Tamim

Reputation: 1036

You can simply apply str_replace for <> sign. Like this way

$rowselected = 'abcd<efgh>lmno';

$rowselected = str_replace('<', '<<span style="color:red">', $rowselected);
$rowselected = str_replace('>', '</span>>', $row);

// result
// "abcd<<span style="color:red"</span>>efgh</span>>lmno" 

Upvotes: 0

Related Questions