Jump to content


Photo

[SOLVED] Show first few character of a string


  • Please log in to reply
4 replies to this topic

#1 abdfahim

abdfahim
  • Members
  • PipPipPip
  • Abd Fahim
  • 535 posts

Posted 21 August 2006 - 04:10 AM

I had the following code
$test="This is the string";
echo $test;
Now I want to echo the first 3 words (or say, first 9 characters) of $test, that is I want to show "This is the" only. How can i do that? Is there any character count and trim method?



#2 logu

logu
  • Members
  • PipPipPip
  • Advanced Member
  • 32 posts

Posted 21 August 2006 - 04:13 AM


use substring funciton

echo substr($test, 0, 9);


#3 tomfmason

tomfmason
  • Staff Alumni
  • Advanced Member
  • 1,696 posts
  • Locationstealing your wifi

Posted 21 August 2006 - 04:14 AM

or
list($a, $b, $c) = explode(" ", $test);
echo "$a, $b, $c";

Hope this helps

Traveling East in search of instruction, and West to propagate the knowledge I have had gained.

current projects: pokersource

My Blog | My Pastebin | PHP Validation class | Backtrack linux


#4 Jervous

Jervous
  • Members
  • Pip
  • Newbie
  • 9 posts

Posted 21 August 2006 - 04:25 AM

To return the first 9 characters:

$test = "This is the string";

$output = substr($test, 0, 8);

echo $output;
// This is t
?>

It doesn't return "he" because PHP counts whitespace as a character.

EDIT: I accidentally pressed Preview so the reply never got sent. Also, you would use 0 and 8, not 9, because 0 - 8 is 9, 0 - 9 is 10.

#5 abdfahim

abdfahim
  • Members
  • PipPipPip
  • Abd Fahim
  • 535 posts

Posted 21 August 2006 - 05:31 AM

You guys are simply GREAT!!! Thanx all.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users