首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >字符串中特定颜色的单词

字符串中特定颜色的单词
EN

Stack Overflow用户
提问于 2022-01-06 10:43:16
回答 1查看 68关注 0票数 -3

我正在使用WordPress。首先,我创建了一个HTML模板,并为字符串中的特定单词创建了一个类。效果很好。

现在我在想,在我从数据库中得到那个字符串之后,是否有可能做到这一点。

代码语言:javascript
复制
<h1 class="heading">Happy<span class="red-color">New Year</span> 2022 !</h1>

当我从数据库中取出字符串时,我会得到“新年”2022年的快乐!

代码语言:javascript
复制
$message = the_field('message'); 

echo $message // Outputs Happy "New year" 2022 ! 

不知道我怎么才能把新年和其他单词涂成"“。

我在谷歌搜索但没有运气。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-06 11:03:50

使用strpos()查找双引号位置的一个简单函数。

代码语言:javascript
复制
$message = 'Happy "New year" 2022 !';

function colourMe($in, $color, $delim = '"')
{
    $new = $in;  // init local

    if ( ($pos = strpos( $in, $delim)) === false ) {
        // nothing to do
        return $new;
    }

    // init position holders
    $first  = null;
    $second = null;
    $first  = strpos($new, $delim);                // find first delimiter
    $second = strpos($new, $delim, $first+1);      // find second delimiter

    if ( $first && $second) ) {
        // if we have 2 delimiters
        $new = sprintf("%s <span class='$color'>%s</span>%s",
                            substr($new, 0, $first-1),
                            substr($new, $first+1, $second-$first-1),
                            substr($new, $second+1)
                );
    }
    return $new;
}

echo colourMe($message, 'red-color');

结果

代码语言:javascript
复制
Happy <span class='red-color'>New year</span> 2022 !

现在,如果您希望它对一个引用的字符串进行多次发生,那么我们可以将它转换为一个递归函数,该函数将一直调用它自己,直到它运行引号字符串集。

代码语言:javascript
复制
$message = 'Happy "New year" 2022! Wishing you a "Prosperous" and "Safe" year.';

function colourMe($in, $color, $delim = '"')
{
    $new = $in;  // init local
/*
    if ( ($pos = strpos( $in, $delim)) === false ) {
        // nothing to do
        return $new;
    }
*/
    // init position holders
    $first  = null;
    $second = null;
    $first  = strpos($new, $delim);                // find first delimiter
    $second = strpos($new, $delim, $first+1);      // find second delimiter

    if ( $first && $second ) {
        // if we have 2 delimiters
        $new = sprintf("%s <span class='$color'>%s</span>%s",
                            substr($new, 0, $first-1),
                            substr($new, $first+1, $second-$first-1),
                            substr($new, $second+1)
                );
    } else {
        // Must be complete
        return $new;
    }
    // Recurse to see if there is another quoted set to change
    return colourMe($new, $color, $delim);
}

echo colourMe($message, 'red-color');

结果

代码语言:javascript
复制
Happy <span class='red-color'>New year</span> 2022! Wishing you a <span class='red-color'>Prosperous</span> and <span class='red-color'>Safe</span> year.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70605914

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档