我正在使用WordPress。首先,我创建了一个HTML模板,并为字符串中的特定单词创建了一个类。效果很好。
现在我在想,在我从数据库中得到那个字符串之后,是否有可能做到这一点。
<h1 class="heading">Happy<span class="red-color">New Year</span> 2022 !</h1>当我从数据库中取出字符串时,我会得到“新年”2022年的快乐!
$message = the_field('message');
echo $message // Outputs Happy "New year" 2022 ! 不知道我怎么才能把新年和其他单词涂成"“。
我在谷歌搜索但没有运气。
发布于 2022-01-06 11:03:50
使用strpos()查找双引号位置的一个简单函数。
$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');结果
Happy <span class='red-color'>New year</span> 2022 !现在,如果您希望它对一个引用的字符串进行多次发生,那么我们可以将它转换为一个递归函数,该函数将一直调用它自己,直到它运行引号字符串集。
$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');结果
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.https://stackoverflow.com/questions/70605914
复制相似问题