使用PHP显示动态突出显示的字符串

该功能可能用途有限,但可以在您的标题中创建一些整洁的效果。它的工作原理是使用空格将字符串分成几小段,然后将其重新放回两部分。第一部分是正常的,但是第二部分将被包裹在span元素中。通过使用此功能,您可以通过将前半部分的样式与后半部分的样式不同来在标题中创建有趣的效果。

/**
*使用span HTML元素高亮显示字符串的后半部分。
*如果字符串中有空格,则将单词一分为二
*(大致)并分别打印这两部分。
*如果字符串中有任何HTML,则拒绝该字符串并返回原始字符串。
 *
 * @param string $string The string to be used.
 *
 * @return string Either the original string or the altered string depending
 *                on what the inputted string consisted of.
 */
function text_split_highlight($string) {
    if (preg_match('/<\/?[^>]>/', $string) == 0 && preg_match('/\s/', $string) != 0) {
        $split = preg_split('/\s/', $string);
        $first_part = array_slice($split, 0, floor(count($split) / 2));
        $second_part = array_slice($split, floor(count($split) / 2));
        return implode(' ', $first_part) . ' <span>' . implode(' ', $second_part) . '</span>';
    }
    else {
        return $string;
    }
}

如果字符串中有任何HTML,该函数将无法正常工作,因为它将创建非法嵌套的HTML标签,因此它将在尝试拆分字符串之前检查HTML标签的存在。如果有任何HTML标记,或者字符串中没有空格,则原始字符串将原样返回。以下是该函数的一些示例:

print text_split_highlight('Title'); // Title
print text_split_highlight('Two Words'); // Two <span>Words<span>
print text_split_highlight('Three Word Title'; // Three <span>Word Title<span>
print text_split_highlight('Four Words In Title'); // Four Words <span>In Title<span>
print text_split_highlight('Five Words In The Title'); // Five Words <span>In The Title<span>
print text_split_highlight('All Of Six Words In Title'); // All Of Six <span>Words In Title<span>
print text_split_highlight('<p>HTML In String</p>'); // HTML In String);