FRIHOSTFORUMSSEARCHFAQTOSBLOGSCOMPETITIONS
You are invited to Log in or Register a free Frihost Account!


PHP ristriction on Output





moejoe
Hi Guys,

Is there a function that can restrict output of characters from a string?

For Example

$string = "Hi Guys, Nice Meeting You"

It has 25 characters,
How to i use php to ristrict it to 5 characters and leave it with a '...' trailing

This is how i want it to output

>> "Hi Gu..."

Thanks for your help!
santium
Code:

<?php
$string = "Hi Guys, Nice Meeting You";
echo substr($string, 0, 5)."...";
?>


Here's also the code to do 5 words instead, because 5 characters is just kinda wierd.
Code:

<?php
$string = "Hi Guys, Nice Meeting You";
$newstring = explode($string, " ");
 for ($i = 0; $i <= 5; $i++) {
  $display = $display." ".$newstring[$i];
 }
 echo $display."...";
?>
hexkid
You don't want to restrict something like "Me too!" (to "Me to...").
I'd use santium's code with a further test
Code:
<?php
define('MAX_STRING_LENGTH', '5');
$string = "Me too!";
if (strlen($string) <= MAX_STRING_LENGTH + 3) {
  echo $string;
} else {
  echo substr($string, 0, MAX_STRING_LENGTH) . "...";
}
santium
hexkid wrote:
You don't want to restrict something like "Me too!" (to "Me to...").
I'd use santium's code with a further test
Code:
<?php
define('MAX_STRING_LENGTH', '5');
$string = "Me too!";
if (strlen($string) <= MAX_STRING_LENGTH + 3) {
  echo $string;
} else {
  echo substr($string, 0, MAX_STRING_LENGTH) . "...";
}

Good suggestion.. I didn't even think about that.. I just followed the assumption that something that was to be limited wouldn't be smaller then the limiting amount.
ritesh26
hi you can use this function also :

Code:

<?php
define('MAX_STRING_LENGTH', '5');
$string = "Hi Guys, Nice Meeting You";

function getString($string){

  return (substr($string, 0, MAX_STRING_LENGTH) . "...");

}

getString($string);
?>
 
hexkid
ritesh26 wrote:
Code:

<?php
define('MAX_STRING_LENGTH', '5');
$string = "Hi Guys, Nice Meeting You";

function getString($string){

  return (substr($string, 0, MAX_STRING_LENGTH) . "...");

}

getString($string);
?>
 
Code:
<?php
if (getString('42') == '42...') {
  echo 'Oops :)';
}
?>
Related topics
changing output but not action="filename.php" ...H
Need help fixing my php file
Dynamic PHP Images
RSS
PHP Test File
Is there anything can make my PHP codes slim?
FriHost PHP Parser doesn´t work?
Jamatus' Dynamic image store
Including Rank
AJAX tutorial [2nd part now updated]
Where;s better way using javascript link or write inside htm
redirection
making the last 5 active topics appear on my homepage?
Site load in half time (with no browser compatibility issue)
Reply to topic    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.