views:

365

answers:

10

hi, i want only the first word of a variable.. example input:

<?php $myvalue = 'Test me more'; ?>

the output should only "Test", the first word of the input.. how can i do this?

+2  A: 
<?php
  $value = "Hello world";
  $tokens = explode(" ", $value);
  echo $tokens[0];
?>

Just use explode to get every word of the input and output the first element of the resulting array.

Ulf
A: 

You could do

echo current(explode(' ',$myvalue));
AntonioCS
+8  A: 

You can use the explode function as follows:

$myvalue = 'Test me more';
$arr = explode(' ',trim($myvalue));
echo $arr[0]; // will print Test
codaddict
Since the OP explicitly states the *first* word, this is also a nice method: `list($first_word) = explode(' ', trim($myvalue));`
Dennis Haarbrink
A: 
$input = "Test me more";
echo preg_replace("/\s.*$/","",$input); // "Test"
markcial
+2  A: 

If you have PHP 5.3

$myvalue = 'Test me more';
echo strstr($myvalue, ' ', true);

The alternative is something like:

$i = strpos($myvalue, ' ');
echo substr($myvalue, 0, $i !== false ? $i : strlen($myvalue));

Or using explode, which has so many answers using it I won't bother pointing out how to do it.

Yacoby
+1 for not using explode or regex (both inappropriate imho). Another alternative would be to use strstr with str_replace, replacing the part after the needle from strstr with nothing.
Gordon
A: 
$str='<?php $myvalue = Test me more; ?>';
$s = preg_split("/= *(.[^ ]*?) /", $str,-1,PREG_SPLIT_DELIM_CAPTURE);
print $s[1];
ghostdog74
+1  A: 

There is a string function (strtok) which can be used to split a string into smaller strings (tokens) based on some separator(s). For the purposes of this thread, the first word (defined as anything before the first space character) of Test me more can be obtained by tokenizing the string on the space character.

<?php
$value = "Test me more";
echo strtok($value, " "); // Test
?>

For more details and examples, see the strtok PHP manual page.

salathe
+3  A: 

Using split function also you can get the first word from string.

<?php
$myvalue ="Test me more";
$result=split(" ",$myvalue);
echo $result[0];
?>
rekha_sri
A: 

$myvalue = 'Test me more'; echo strstr($myvalue, ' ', true);

IF chage to this: $myvalue = 'Test me more'; echo strstr($myvalue, '', true);

will print "T" RIGHT?

JIMMY
A: 

personally strsplit / explode / strtok does not support word boundaries, so to get a more accute split use regular expression with the \w

preg_split('/[\s]+/',$string,1);

This would split words with boundaries to a limit of 1.

RobertPitt