Ask an expert
Question

12 Jan 2013

JaJPIOTramcPbwC
Task: Display just the first name from the full name which is stored in the foramt of LastName, FirstName MiddleName(optional) .Solution in PHP: Use of PHP strpos() and substr() functions.The syntax of these functions are:int strrpos ( string $haystack , string $needle [, int $offset] ) returns the position of needle in the haystack string starting from $offset position. Default value of $offset is 0.string substr ( string $string , int $start [, int $length ] ) returns a portion of the stringPHP code:$string= $fullname  // $fullname may have Kennedy, John F or Obama, Barack or $start=strpos($string,'','')+2  // find the position of ,'' and skip comma &  spaceif (strpos($string,'' ,$start)) { // case: there is a space after first name $length=strpos($string,'' ,$start) $start  // get the length of first name} else { // case: no space after first name which means no middle name $length=strlen($string)  // definitely greater or equal to length of firstmane}echo substr($string, $start, $length)  // displays the first name, John or Barack or
Voting Booth
Have you entered our Health of the Nation survey?
Please select an option Oops! Something went wrong, please try again later.
Results
Yes
33% - 9324 votes
No
67% - 18748 votes
Vote