Display A Dynamicly Highlighted String With PHP

7th February 2011 - 2 minutes read time

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.

  1. /**
  2.  * Highlight the second half of a string with a span HTML element.
  3.  * If the string has a space in it then split the words in half
  4.  * (roughly) and print out the two parts separately.
  5.  * If there is any HTML in the string then reject it and return the original.
  6.  *
  7.  * @param string $string The string to be used.
  8.  *
  9.  * @return string Either the original string or the altered string depending
  10.  * on what the inputted string consisted of.
  11.  */
  12. function text_split_highlight($string) {
  13. if (preg_match('/<\/?[^>]>/', $string) == 0 && preg_match('/\s/', $string) != 0) {
  14. $split = preg_split('/\s/', $string);
  15. $first_part = array_slice($split, 0, floor(count($split) / 2));
  16. $second_part = array_slice($split, floor(count($split) / 2));
  17. return implode(' ', $first_part) . ' <span class="highlight">' . implode(' ', $second_part) . '</span>';
  18. }
  19. else {
  20. return $string;
  21. }
  22. }

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:

  1. print text_split_highlight('Title'); // Title
  2. print text_split_highlight('Two Words'); // Two <span class="highlight">Words<span>
  3. print text_split_highlight('Three Word Title'; // Three <span class="highlight">Word Title<span>
  4. print text_split_highlight('Four Words In Title'); // Four Words <span class="highlight">In Title<span>
  5. print text_split_highlight('Five Words In The Title'); // Five Words <span class="highlight">In The Title<span>
  6. print text_split_highlight('All Of Six Words In Title'); // All Of Six <span class="highlight">Words In Title<span>
  7. 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.