If I use the same name for both the first and last name or use a ' my name splitting function is not working as intended. How can I make it work even if the string looks like:
Jeanne D'Arc
Lang Lang
The first will return the whole name in the $last_name string and the second one will return only one name in the $last_name string.
function split_name($name) {
$name = trim($name);
$last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name);
$first_name = trim( preg_replace('#'.$last_name.'#', '', $name ) );
return array($first_name, $last_name);
}
Thanks!
Like Sergio answer. Take a look what is already possible to do with PHP. explode do the same thing as your split_name.
Source:
http://php.net/manual/fr/function.explode.php
This worked for me! It is assuming that you only have one last name and that it's the last word of the string, but the user will be able to edit this anyway so it's just a starting point. Thank you guys.
function split_name($name) {
$parts = explode(" ", trim($name));
$num = count($parts);
if($num > 1)
{
$lastname = array_pop($parts);
}
else
{
$lastname = '';
}
$firstname = implode(" ", $parts);
return array($firstname, $lastname);
}
Related
i have been trying to get the email address which has domains ends with .edu only using code below
$email = $_REQUEST['email'];
$school = substr($email, strpos($email, "#") + 1);
is there any way?
You just need to make a substring including the last 3 chars of the current string.
<?php
$tld = substr($email, strlen($email)-2, 3); // three last chars of the string
if ($tld = "edu") {
// do stuff
}
?>
It Should be work for get your domain name and domain extension:
$email = 'test#website.edu';
$getDomain = explode('#', $email);
$explValue = explode('.', $getDomain[1], 2);
print_r($explValue);
The out put is:
Array ( [0] => website [1] => edu )
After that you can check with
if($explValue[1] == 'edu'){
//your code here
}
If .edu is the last part of the email address, you could use strlen and substr:
$email = "test#test.edu";
$end = ".edu";
$string_end = substr($email, strlen($email) - strlen($end));
if ($end === $string_end) {
// Ok
}
Maybe it is also an option to use explode and split on #. Then use explode again and split on a dot and check if the array returned contains edu:
$strings = [
"test#test.edu",
"test#test.edu.pl",
"test#test.com"
];
foreach ($strings as $string) {
if (in_array("edu", explode(".", explode("#", $string)[1]))) {
// Etc..
}
}
Demo
strpos($email, ".edu."); it should be work.
for example gensek#metu.edu.tr
You can use substr And get last 4 characters if this is valid as per your requirement so the email is valid else it not.
$string = "xyzasd.edu";
echo $txt = substr($string,-4);
if($txt == ".edu"){
//Valid
}else{
//Not Valid
}
URL of my site is:
http://mc.net46.net/ + folderName + fileName
For example:
http://mc.net46.net/mc/file01.php
http://mc.net46.net/mx/file05.php
folderName is always two characters long.
$address = 'http://mc.net46.net'.$_SERVER["REQUEST_URI"];
result: http://mc.net46.net/mc/file01.php - ok
$fname = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
result: file01.php - ok
Two questions:
Is this the correct way to get $address and $fname ?
How to get folderName?
Try this for another way to get your dynamic file names:
<?php
$fname = "http://mc.net46.net/mc/file01.php";
OR
$fname = $_SERVER["REQUEST_URI"];
$stack = explode('/', $fname);
$ss = end($stack);
echo $ss;
?>
Here for $fname you can use this $fname = explode('/', $_SERVER["REQUEST_URI"]);
Getting the address looks correct to me. However, you can get the $fname and the folder name easily using explode, and array_pop
$stack = explode('/', $_SERVER["REQUEST_URI"]);
$fname = array_pop($stack);
$folderName = array_pop($stack);
EDIT:
Explaining how does this work: the explode function will split the URI into ['', 'mc', 'file01.php'] for example. Now the function array_pop takes out the last element ($fname = 'file01.php') from the array, that means after the first call the array will be ['', 'mc'], and repeating the same action in the second call will will take out ($folderName = 'mc') as it will be the last element in the array and leave [''].
Use basename
$fname = basename("http://mc.net46.net/mc/file01.php")
RESULT = file01.php
DEMO
try
function getUriSegment($n) {
$segs = explode("/", parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
return count($segs)>0 && count($segs)>=($n-1)?$segs[$n] : '';
}
// if the url is http://www.example.com/foo/bar/wow
echo getUriSegment(1); //returns foo
echo getUriSegment(2); //returns bar
for more :- http://www.timwickstrom.com/server-side-code/php/php-get-uri-segments/
There seems to be many acceptable email address formats in the To: and From: raw email headers ...
person#place.com
person <person#place.com>
person
Another Person <person#place.com>
'Another Person' <person#place.com>
"Another Person" <person#place.com>
After not finding any effective PHP functions for splitting out names and addresses, I've written the following code.
You can DEMO IT ON CODEPAD to see the output...
// validate email address
function validate_email( $email ){
return (filter_var($email, FILTER_VALIDATE_EMAIL)) ? true : false;
}
// split email into name / address
function email_split( $str ){
$name = $email = '';
if (substr($str,0,1)=='<') {
// first character = <
$email = str_replace( array('<','>'), '', $str );
} else if (strpos($str,' <') !== false) {
// possibly = name <email>
list($name,$email) = explode(' <',$str);
$email = str_replace('>','',$email);
if (!validate_email($email)) $email = '';
$name = str_replace(array('"',"'"),'',$name);
} else if (validate_email($str)) {
// just the email
$email = $str;
} else {
// unknown
$name = $str;
}
return array( 'name'=>trim($name), 'email'=>trim($email) );
}
// test it
$tests = array(
'person#place.com',
'monarch <themonarch#tgoci.com>',
'blahblah',
"'doc venture' <doc#venture.com>"
);
foreach ($tests as $test){
echo print_r( email_split($test), true );
}
Am I missing anything here? Can anyone recommend a better way?
I have managed to make one regex to your test cases:
person#place.com
person <person#place.com>
person
Another Person <person#place.com>
'Another Person' <person#place.com>
"Another Person" <person#place.com>
using preg_match with this regex will surely help you bit.
function email_split( $str ){
$sPattern = "/([\w\s\'\"]+[\s]+)?(<)?(([\w-\.]+)#((?:[\w]+\.)+)([a-zA-Z]{2,4}))?(>)?/g";
preg_match($sPattern,$str,$aMatch);
if(isset($aMatch[1]))
{
echo $aMatch[1] //this is name;
}
if(isset($aMatch[3]))
{
echo $aMatch[3] //this is EmailAddress;
}
}
Note: I just noticed that single "person" i.e. your third test case could be discarded with this regex (just that because of space constraint in regex) so,at first line of your email_split function, append space at last place of your string.
Then it would be bang on target.
Thanks, Hope this helps.
Code I tried:
<?php
// validate email address
function validate_email($email) {
return (filter_var($email, FILTER_VALIDATE_EMAIL)) ? true : false;
}
// split email into name / address
function email_split($str) {
$str .=" ";
$sPattern = '/([\w\s\'\"]+[\s]+)?(<)?(([\w-\.]+)#((?:[\w]+\.)+)([a-zA-Z]{2,4}))?(>)?/';
preg_match($sPattern, $str, $aMatch);
//echo "string";
//print_r($aMatch);
$name = (isset($aMatch[1])) ? $aMatch[1] : '';
$email = (isset($aMatch[3])) ? $aMatch[3] : '';
return array('name' => trim($name), 'email' => trim($email));
}
// test it
$tests = array(
'person#place.com',
'monarch <themonarch#tgoci.com>',
'blahblah',
"'doc venture' <doc#venture.com>"
);
foreach ($tests as $test) {
echo "<pre>";
echo print_r(email_split($test), true);
echo "</pre>";
}
Output I got:
Array
(
[name] =>
[email] => person#place.com
)
Array
(
[name] => monarch
[email] => themonarch#tgoci.com
)
Array
(
[name] => blahblah
[email] =>
)
Array
(
[name] => 'doc venture'
[email] => doc#venture.com
)
How about this:
function email_split($str) {
$parts = explode(' ', trim($str));
$email = trim(array_pop($parts), "<> \t\n\r\0\x0B");
$name = trim(implode(' ', $parts), "\"\' \t\n\r\0\x0B");
if ($name == "" && strpos($email, "#") === false) { // only single string - did not contain '#'
$name = $email;
$email = "";
}
return array('name' => $name, 'email' => $email);
}
Looks like this is about twice as fast as the regex solution.
Note: the OPs third test case (for my purposes) is not needed. But in the interest of answering the OP I added the if stmt to produce the OPs expected results. This could have been done other ways (check the last element of $parts for '#').
use preg_match in php, http://php.net/manual/en/function.preg-match.php
or in my opinion, you can make your own function (let say get_email_address), it catch # character and then get the 'rest-left-string' from # until '<' character and 'rest-right-string' from # until '>' character.
for example, string monarch <themonarch#tgoci.com> will return 'rest-left-string' = themonarch and 'rest-right-string' = tgoci.com . finally, your function get_email_address will return themonarch#tgoci.com
hopefully it help.. :)
unfortunately the regex fails in a couple of conditions of the fullname:
non alphanumeric chars (eg. "Amazon.it")
non printable chars
emojs
i adjusted the expression this way
$sPattern = '/([^<]*)?(<)?(([\w-\.]+)#((?:[\w]+\.)+)([a-zA-Z]{2,4}))?(>)?/';
and now all chars are correctly recognized and splitted.
tested with
$address = "Test User # `` . !! 🔥 <test#email.com";
after 7 years, hope this helps :)
I have to split a user name into first name and last name, but I don't know how many elements there may be in the name.
I have some working code, but it seems like it could be optimized.
Does anyone have any suggestions to make this more elegant?
function createMoodleUserNames($fullname){
$names = explode(' ',$fullname);
$prefixes = array('Dr.','Ms.','Mr.','Mrs.');
$names = explode(' ',$name);
$i = 0;
if(in_array($names[0],$prefixes)){
$firstname = $names[0].' '.$names[1];
unset($names[0]);
unset($names[1]);
}else{
$firstname = $names[0];
unset($names[0]);
}
$lastname = '';
while($i < count($names)){
$lastname .= ' '.$names[$i];
$i++;
}
$output = array();
$output[0] = $firstname;
$output[1] = $lastname;
return $output;
}
I am not sure how complex data are you parsing, but this straightforward solution might suit you:
<?php
function parseName($fullName) {
$parts = preg_split('~\s+~', $fullName);
$result = array();
if (!preg_match('~(dr|mr|ms|mrs)\.?~', strToLower($parts[0]))) {
$result[] = $parts[0];
} else {
$result[] = $parts[1];
}
$result[] = end($parts);
return $result;
}
Ignores first part if it is a recognized prefix and takes family name from the very last part.
I think line 7, $names = explode(' ',$name); needs to be removed.
As far as optimizing, the code is pretty simple, so if it is doing what you need (ie. your test cases return results you are happy with) then the only optimization I would suggest is
$lastname = implode(' ', $names);
instead of your while loop. Since you are using unset to remove items already processed, $names will only be the remaining items (lastname). Though this is micro-optimizing, it will make your code a little cleaner and remove some cruft.
What's the best way to accomplish the following.
I have strings in this format:
$s1 = "name1|type1"; //(pipe is the separator)
$s2 = "name2|type2";
$s3 = "name3"; //(in some of them type can be missing)
Let's assume nameN / typeN are strings and they can not contain a pipe.
Since I need to exctract the name / type separetly, I do:
$temp = explode('|', $s1);
$name = $temp[0];
$type = ( isset($temp[1]) ? $temp[1] : '' );
Is there an easier (smarter whatever faster) way to do this without having to do isset($temp[1]) or count($temp).
Thanks!
list($name, $type) = explode('|', s1.'|');
Note the order of arguments for explode()
list($name,$type) = explode( '|',$s1);
$type will be NULL for $s3, though it will give a Notice
I'm a fan of array_pop() and array_shift(), which don't error out if the array they use is empty.
In your case, that would be:
$temp = explode('|', $s1);
$name = array_shift($temp);
// array_shift() will return null if the array is empty,
// so if you really want an empty string, you can string
// cast this call, as I have done:
$type = (string) array_shift($temp);
There is not need to do isset since $temp[1] will exist and content an empty value. This works fine for me:
$str = 'name|type';
// if theres nothing in 'type', then $type will be empty
list($name, $type) = explode('|', $str, 2);
echo "$name, $type";
if(strstr($temp,"|"))
{
$temp = explode($s1, '|');
$name = $temp[0];
$type = $temp[1];
}
else
{
$name = $temp[0];
//no type
}
Maybe?