How To Limit Your Text’s Characters using PHP

62
rate or flag this page

By MistreX

Syntax

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 !)


Exemple1

< ?php

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

?>


That exemple 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 exemple2.

Exemple2

<?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

Any question I am here

poll

What You think about that lesson ?

  • It's Very good
  • Not bad but need something else
  • bad
See results without voting

Print   —   Rate it:  up  down  flag this hub

Comments

RSS for comments on this Hub

No comments yet.

Submit a Comment

Members and Guests

Sign in or sign up and post using a hubpages account.


optional


  • No HTML is allowed in comments, but URLs will be hyperlinked
  • Comments are not for promoting your hubs or other sites

working