Home>

I want to change the color of multiple specified strings.
For example, when writing the sentence "a, or c such as b."
I want to change the letters a, b, and c to the same color.
I found out how to replace a string with a string as follows ...
How can I change the color?

<? php
$str = 'a, or c, such as b. ';
$key = array ('/ a /', '/ b /', '/ c /');
$replace = 'A';
$str_grept = preg_replace ($key, $replace, $str);
echo $str_grept;
?>
php
  • Answer # 1

    You can do something like that below.

    <style>
    .hoge {
        color: red;
    }
    </style>
    <? php
    $str = 'a, or c, such as b. ';
    $key = array ('/ a /', '/ b /', '/ c /');
    $str_grept = preg_replace ($key, '<SPAN CLASS = "hoge">$0</SPAN>', $str);
    echo $str_grept;


    Output result

    <SPAN CLASS = "hoge">a</SPAN>or<SPAN CLASS = "hoge">b</SPAN><SPAN CLASS = "hoge">c</SPAN> ;.

    $0 matches the character you entered.
    (There are cases where 0 alone is not good, so it must be changed depending on the replacement target and requirements.)

    Notes

    The only thing that says "it looks like" is that the tags and attributes are capitalized.
    Even if you put the first argument in the array, it will only be replaced one by one from the first, so if you make the html tag and attribute lowercase, class c will be the replacement target.
    Even if you try to change the character color other than this method, it may eventually get caught somewhere, and it will only be for simple substitution like this time, so it may not be a very versatile way Hmm.

    Maybe a more versatile answer might come
    My answer may be a little more helpful as a reference.

    PHP manual: preg_replace ()

    PHP regular expression notes

Related articles