advertisement
Question
Posted by: Madhu | 2013/01/12

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

Not what you were looking for? Try searching again, or ask your own question

Have your say

Thanks for commenting! Your comment will appear on the site shortly.
Thanks for commenting! Your comment will appear on the site shortly.
advertisement