iamtom Posted December 20, 2008 Share Posted December 20, 2008 Don't know if this is new , probably not, but can't find exactly what I am looking for. I have a form that submits the field "name", to php script. The name field has full name in it, I want to select the last part of the name filed and create a new filed "LName". I don't know how to use explode, trim or preg to select data after a 'space' character. I tried this: (where Name is "xxxxx yyyyy") <?php //$arr = explode(' ',ltrim(rtrim($Name,''),'')); //$LName = $arr[1],true; ?> but it give me error codes for unexpected "," . I need just the yyyyy. Any help would be appreciated Quote Link to comment https://forums.phpfreaks.com/topic/137823-parse-name-field/ Share on other sites More sharing options...
.josh Posted December 20, 2008 Share Posted December 20, 2008 did you actually read the error? It's telling you there's an unexpected comma. You can't use commas in variable assignments like that. $LName = $arr[1]; Quote Link to comment https://forums.phpfreaks.com/topic/137823-parse-name-field/#findComment-720315 Share on other sites More sharing options...
nrg_alpha Posted December 20, 2008 Share Posted December 20, 2008 iamtom, There are a few ways you can solve this (with regex and non-regex solutions). Assuming the name is 'firstName lastName' (where you want to get only the lastName part); Non-regex solution: $str = ' firstName lastName '; // just to complicate things, let's pretend there are spaces before AND after entry $str = trim($str, ' '); $arr = explode(' ', $str); echo $arr[1]; Output: lastName Regex solution: $str = ' firstName lastName '; preg_match('#(\S+)\s*$#', $str, $match); echo $match[1]; Same output as first solution. This pattern basically captures (from the end, spaces optional), any non-space character one or more times. As a result, this pattern will handle entries with an accidental space (or spaces) at the very beginning and / or end (after the lastName part). In fact, either solution provided should work regardless to any extra initial or trailing spaces (whether they exist or not). EDIT - The non-regex could be slightly simplified: $str = ' firstName lastName '; $arr = explode(' ', trim($str, ' ')); // combine the trim function here... echo $arr[1]; Quote Link to comment https://forums.phpfreaks.com/topic/137823-parse-name-field/#findComment-720345 Share on other sites More sharing options...
DarkWater Posted December 20, 2008 Share Posted December 20, 2008 list($fname, $lname) = explode(' ', trim($Name)); =/ Why, in your code, did you put: , true After your variable assignment? Quote Link to comment https://forums.phpfreaks.com/topic/137823-parse-name-field/#findComment-720347 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.