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?
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?
<?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.
You can use the explode function as follows:
$myvalue = 'Test me more';
$arr = explode(' ',trim($myvalue));
echo $arr[0]; // will print Test
$input = "Test me more"; echo preg_replace("/\s.*$/","",$input); // "Test"
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.
$str='<?php $myvalue = Test me more; ?>';
$s = preg_split("/= *(.[^ ]*?) /", $str,-1,PREG_SPLIT_DELIM_CAPTURE);
print $s[1];
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.
Using split function also you can get the first word from string.
<?php
$myvalue ="Test me more";
$result=split(" ",$myvalue);
echo $result[0];
?>
$myvalue = 'Test me more'; echo strstr($myvalue, ' ', true);
IF chage to this: $myvalue = 'Test me more'; echo strstr($myvalue, '', true);
will print "T" RIGHT?
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.