Showing posts with label plugin. Show all posts
Showing posts with label plugin. Show all posts

Tuesday, July 12, 2011

PHP truncate words(shorten text string)

We want to truncate/shortern a string of text into a specific number of characters and add three dots (...) to the end. For example, we have a string "For he was looking forward to the city with foundations, whose architect and builder is God."; and we want to show it as "For he was looking forward to the city with foundations..."

This requirement can be more generic that we want to truncate words into a given $max number of characters and add $symbol to the end. For our example, $max = 60 and $symbol = '...'

Let's see how we can do it.

function truncate($text, $max, $symbol)
{
                //step 1: we get the part of the text with maximum $max number of characters
                $sub = substr($text, 0, $max);
                //step 2: we find the position of last occurence of space
                //   this is where we start to truncate the words
                $last = strrpos($sub, ' ');
                //step 3: get the sub string from beginning to the truncate position
                $sub = substr($sub, 0, $last);
                //step 4: padding the sub string with $symbol and return
                return $sub . $symbol;
}

We can try this function
$text = "For he was looking forward to the city with foundations, whose architect and builder is God.";
echo truncate($text, 28, '...');
The result is: For he was looking forward...

The turncate function serves well in most cases and probably is most wildly used, but it does have some minor flaw. If we try
$text = "For he was looking forward to the city with foundations, whose architect and builder is God.";
echo truncate($text, 60, '...');
The result is: For he was looking forward to the city with foundations,...

See the last comma before '...'? If you can accept that, then it is fine. But if we don't want to leave punctuation or other non-word character as the final character, we need to modify our truncate function a bit.

function truncate($text, $max, $symbol)
{
                //step 1: we get the part of the text with maximum $max number of characters
                $sub = substr($text, 0, $max);
                //step 2: we find the position of last occurence of space
                //   this is where we start to truncate the words
                $last = strrpos($sub, ' ');
                //step 3: get the sub string from beginning to the truncate position
                $sub = substr($sub, 0, $last);
                //step 4: remove any non word characters, padd the sub string with $symbol and return
                $sub = preg_replace("/([^\w])$/", "", $sub);
                return $sub . $symbol;
}

The difference is $sub = preg_replace("/([^\w])$/", "", $sub); This will replace any non-word character([^\w]) at the end($) with empty string(""). Now let's try again:
$text = "For he was looking forward to the city with foundations, whose architect and builder is God.";
echo truncate($text, 60, '...');
The result is: For he was looking forward to the city with foundations...

Monday, July 11, 2011

PHP highlight search keywords

Sometimes we may wish to highlight the search keywords(search terms) in the searching result.

For example, there is a string "A cat is a mini tiger. Actually, cat and tiger belong to the same category". We may want to highlight all the 'cat' within this string, but we obviously don't want to highlight the 'cat' in 'category'.

Here is the result of our highlighting.

A cat is a mini tiger. Actually, cat and tiger belong to the same category

Here is how we can do it:

$string = "A cat is a mini tiger. Actually, cat and tiger belong to the same category";
$match  = "cat";
$string = preg_replace("/(\b)($match)(\b)/i", "$1<u>$2</u>$3", $string);

\b is word boundary. This will ensure we only match the 'cat' as a whole word. It can match "cat" or "cat's", but it won't match "category".

If we want to make the word italic. We can do:
$string = preg_replace("/(\b)($match)(\b)/i", "$1<i>$2</i>$3", $string);

Wednesday, July 6, 2011

php wrap lines

PHP's wordwrap() function probably can serve well. But this function will even put paragraphs into one line. We want to wrap our lines based on the given width number, but we also want to make sure that a paragraph starts from a new line and we might also want to do indention.

The logic is below.

1. we want to break the text into paragraphs. This can be done by
$paragraphs = explode("\n", $text);

2. For each paragraph, we break the it into words.
$words = explode(" ", $paragraph);
We also want to indent for each new paragraph: str_repeat("&nbsp;", $indent);

3. For each word, we check if (the length of current line + word length) > $width, if yes, then put the word at the same line; if no, put the word at the next line.

Based on the logic, we can have our own wrapping function

function myWordwrap($text, $width, $indent, $break="\n")
{
   //initialize $wrappedText, which will store the wrapped text
   $wrappedText = "";
   
   //break the text into paragraphs
   $paragraphs = explode("\n", $text);
   foreach($paragraphs as $paragraph)
   {
      //if we do indent, prefix with space
      if ($indent > 0) {
         $wrappedText .= str_repeat("&nbsp;", $indent);
      }
      
      //break a paragraph into words
      $words      = explode(" ", $paragraph);
      $lineLength = $indent;
      foreach($words as $word)
      {
       //get the word length
         $wordLength = strlen($word);
 
         //the current line length cannot be larger than the given width
         if (($lineLength + $wordLength ) < $width)
         {
            $wrappedText .= $word . ' ';
            $lineLength  += $wordLength + 1;
         } else {
            //we have to put the word in a new line
            $wrappedText  = trim($wrappedText);
            $wrappedText .= $break . $word . ' ';
            //update length
            $lineLength = $wordLength;
         }
      }

      $wrappedText  = trim($wrappedText);
      //one paragraph ends, start a new line
      $wrappedText .= $break;
   }

   return $wrappedText;
}