Display A Dynamicly Highlighted String With PHP

This function might be of limited use, but it can create some neat effects in your titles. It works by splitting a string into little bits using the spaces and then puts it back together again into two sections. The first section will be normal, but the second section will be wrapped in a span element. By using this function you can create an interesting effects in your titles by styling the first half differently from the second.

/**
 * Highlight the second half of a string with a span HTML element.
 * If the string has a space in it then split the words in half
 * (roughly) and print out the two parts separately.
 * If there is any HTML in the string then reject it and return the original.
 *
 * @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 class="highlight">' . implode(' ', $second_part) . '</span>';
    }
    else {
        return $string;
    }
}

The function doesn't work that well if there is any HTML in the string as it will create illegally nested HTML tags so it will check for the existence of HTML tags before trying to split the string. If there are any HTML tags, or the string doesn't have any spaces in it, then the original string is returned unchanged. Here are some examples of the function in action:

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

 

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
9 + 4 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.