试着把<span>多个字串的第一个字左右只对两个字串起作用,不能超过两个


Trying to wrap <span> around first word of multiple word strings only works on two word strings and not more than two

我正在尝试围绕多个单词小部件标题的第一个单词进行包装。我使用了这里的答案:

修改Wordpress功能,把一个Span围绕标题的第一个词?

并将其调整为:

function add_label_to_post_title( $title = '' ) {
    $ARR_title = explode(" ", $title);
    if(sizeof($ARR_title) > 1 ) {
        $first_word = "<span>".$ARR_title['0']."</span> ";
        unset($ARR_title['0']);
        return $first_word. implode(" ", $ARR_title);
    } else {
        return $title;
    }
}
add_filter( 'widget_title', 'add_label_to_post_title' );

在两个单词的标题上效果很好。但是,3个或更多的单词标题不受影响。

我试着修改代码:

preg_replace('/(?<='>)'b'w*'b|^'w*'b/', '<span>$0</span>', $string);
从这里

:

使用preg_replace在字符串的第一个单词周围换行-tag

和有相同的结果,对两个单词的标题效果很好,但三个或更多单词的标题不受影响。有人知道为什么吗?

请在

下面找到使用数组的代码片段
function add_label_to_post_title( $title = '' ) 
{
    $ARR_title = explode(" ", $title);
    if(sizeof($ARR_title) > 1 )
    {
        $ARR_title[0] = "<span>".$ARR_title[0]."</span>";
        return implode(" ", $ARR_title);
    }
    else
    {
        return $title;
    }
}
echo add_label_to_post_title ("hi there this is test code");