Jump to content


Photo

Truncate


  • Please log in to reply
2 replies to this topic

#1 Rackspace

Rackspace
  • New Members
  • Pip
  • Newbie
  • 1 posts

Posted 02 March 2006 - 11:48 AM

Hello peeps,
does anyone know a simple way to limit a string to the first word in it?

#2 AndyB

AndyB
  • Staff Alumni
  • Advanced Member
  • 5,465 posts
  • LocationToronto

Posted 02 March 2006 - 12:43 PM

<?php
$mystring = "this is text with spaces";
$words = explode(" ",$mystring); // split into array on space separator
echo $words[0]; // first element of array, i.e. this
?>

Legend has it that reading the manual never killed anyone.
My site

#3 khburres

khburres
  • Members
  • PipPip
  • Member
  • 12 posts

Posted 02 March 2006 - 01:47 PM

[!--quoteo(post=350921:date=Mar 2 2006, 06:48 AM:name=Rackspace)--][div class=\'quotetop\']QUOTE(Rackspace @ Mar 2 2006, 06:48 AM) View Post[/div][div class=\'quotemain\'][!--quotec--]
Hello peeps,
does anyone know a simple way to limit a string to the first word in it?
[/quote]

Another possibility:
<?php
//-- Using string methods
$mystring = "Hello there";
$mystring = substr($mystring,0,strpos($mystring,' '));
echo $mystring;

//-- Using regular expressions
$str = "Hi there";
$pattern = '/^([\w]*)(\b)/';
preg_match($pattern, $str, $matches);
echo $matches[1];
?>

I admit, I'm not nearly an expert with regular expressions, so there could be a better way than that proposed.
He who guards his mouth and his tongue keeps himself from calamity.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users