Jump to content

Parse Name Field


iamtom

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/137823-parse-name-field/
Share on other sites

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];

Link to comment
https://forums.phpfreaks.com/topic/137823-parse-name-field/#findComment-720345
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.