Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.