Wednesday, May 2, 2012

How To Limit Your Text’s Characters using PHP

Limiting a text characters is displaying a limit number a characters from a text ( not to show all the text )

The function we will use for that is substr and the syntax is:

substr($message, start, length) ;

$message : we put the text into that variable.

Start : Where you want to start dislaying text from ( put the number of character starting by 0 ).

Length : Define how many character you want to display.

( be sure that the Length is less than the text character’s number !)

Example1

< ?php

$length = 12 ;
$text = "Learn PHP With MistreX" ;
$display = substr($text, 0, $length) ;
echo $display;
echo "..." ;

?>


That example will show that result :

Learn PHP Wi...

----------------------------

Because : (Learn PHP Wi) = 12 Character

But we dont wanna cut the word (with) or any other word on the text !

To do that we will add a Conditional Statement so that if the last character is not a space ( it’s a letter ) then length++ ( length = length +1 )

Look at example2.
Example2

<?php

/***************************************************/

///// How To Limit Your Text’s Characters using PHP //////

////////////////////// By : MistreX ///////////////////

/**************************************************/

$length =10; // how many character you want to display.

$text = "Learn PHP With MistreX" ; // The Text.


$check = substr($text,$length,1); // To find what is the charater after the last shown character

if($check != " "){ // if the character is not a space ( it is be a letter ) we have to show it !

while ( $check != " "){ // we will do that while the character is a letter

$length = $length + 1 ; // By MistreX

$check = substr($text,$length,1); // To find what is the charater again

}

}

$display = substr($text, 0, $length);

echo $display;

echo "...";

?>

And Now the result will be correct

No comments:

Post a Comment