<?php
$string1 = "FARMER John";
$string2 = "OVERMARS DE Rafa";
$string3 = "VAN DER BELT Dick";
?>
To save the first and lastname in a mysql database I need to split the string.
Above you can see a few examples.
What is the best way to split this string, note that the lastname is in caps.
Result should be:
ResultString1: John FARMER
ResultString2: Rafa OVERMARS DE
ResultString3: Dick VAN DER BELT
This is a really bad idea.
There are tons of things that can go wrong if you're purely relying on letter case to signify something. And saving it all in another string just perpetuates the problem.
That said, you can mitigate (a small amount of) the badness by storing the new values separately, so as not to pass along unstructured information to the next unfortunate person who has to maintain your database. This code does that, while also allowing for multi-word first names (like "John Paul" or such).
I also made it handle these in array form, since I assume that you probably want to handle more than three names.
<?php
$string1 = "FARMER John";
$string2 = "OVERMARS DE Rafa Dafa";
$string3 = "VAN DER BELT Dick";
$strings = array(array('orig'=>$string1), array('orig'=>$string2), array('orig'=>$string3));
foreach($strings as $key=>$val){
$oldwords = explode(' ',$val['orig']);
foreach($oldwords as $word){
if(preg_match('/[a-z]/',$word)){
$firstname .= " ".$word;
}else{
$lastname .= " ".$word;
}
}
$firstname = trim($firstname);
$lastname = trim($lastname);
$strings[$key]['newfirst'] = $firstname;
$strings[$key]['newlast'] = $lastname;
$firstname = "";
$lastname = "";
}
print_r($strings);
?>
Follow the following steps:
Convert string to array when space appears.
Pop out the last array element(apparently the first name) using array_pop.
Insert the popped out name in front using array_unshift
Convert array back to string.
$string3 = "VAN DER BELT Dick";
$arr = explode(" ", $string3);
array_unshift($arr, array_pop($arr));
echo implode(" ", $arr); // Dick VAN DER BELT
$arr = explode(" ", $string3);
$last_word = array_pop($arr);
$final_string = ucfirst($last_word)." ".strtoupper(implode(" ", $arr));
echo $final_string;
As others said, your problem description is rather vague. However with a fixed pattern like this, you could very well split the names via a regular expression (given the surname is always in uppercase):
<?php
$strings = array("FARMER John", "OVERMARS DE Rafa", "VAN DER BELT Dick");
$regex = '~^([A-Z ]+\b)(\w+)$~';
foreach ($strings as $string) {
if(preg_match($regex, $string, $match)) {
$surname = trim($match[1]);
$forename = trim($match[2]);
echo "Surname: $surname, Forename: $forename\n";
}
}
?>
See a working demo on ideone.com (plus the one on regex101.com).
Related
I know this question has been answered in here before, but the different functions suggested in the other questions have not been to any help for me - and I´ve tried some few.
I have for example this string with three names that outputs from my database every time it's being loaded:
$string = "Joe Hansen, Carl Clarkson Clinton, Miranda Cobweb Fisher-Caine";
I only want it to output:
$string = "Joe, Carl, Miranda";
I tried this one: click - but it only outputs the first name in some situations and not every time. Is there a easy solution to this one? I also tried explode and implode but did not get that to work either.
Something like this?
<?php
$string = "Joe Hansen, Carl Clarkson Clinton, Miranda Cobweb Fisher-Caine";
$names = explode(",", $string);
$firstNames = array_map(function($name) {
$split = explode(" ", trim($name));
return reset($split);
}, $names);
echo implode(", ", $firstNames);
First you can explode() string with comma , separated. Then go through the loop.
and get first name in the array with substr() and then implode with ,.
$string = "Joe Hansen, Carl Clarkson Clinton, Miranda Cobweb Fisher-Caine";
$names = explode(",", $string);
$firstNames = array();
foreach($names as $name){
$firstNames[] = substr(trim($name), 0, strpos(trim($name), " "));
}
echo implode(", ", $firstNames);
First explode the string on ,, loop through the array, then push the elements in a new array and implode it.
$string = "Joe Hansen, Carl Clarkson Clinton, Miranda Cobweb Fisher-Caine";
$new_string=explode(",",$string);
$slipt_arr=explode(" ",$new_string);
$final_arr=array();
foreach ($new_string as $value)
{
$elements=array_filter(explode(" ",$value));
array_push($final_arr,current($elements));
}
echo implode(", ",$final_arr);
I have an array which contains the full name. I know how to display the last name which basically resides in the 1st index. How can I display the rest of the values after the last name?
$fullname = array('fullname' => 'POTTER Harry James');
$res = implode("", $fullname);
$name = preg_split("/[\s,]+/", $res);
$lname = $name[0];
What i did in the first name:
$fname = $name[1]. " ".$name[2];
It works fine, but is there a cleaner way to do that? I mean, what if the user has more than 2 first names?
Thanks.
I suggest to use explode() function:
<?php
$fullname = array('fullname' => 'POTTER Harry James');
$parts = explode(' ', $fullname['fullname']);
var_dump($parts);
?>
Shows:
array(3) {
[0]=>
string(6) "POTTER"
[1]=>
string(5) "Harry"
[2]=>
string(5) "James"
}
You might use any part of $parts in a way, that you need.
<?php
$a = array_shift($parts);
$b = implode(' ', $parts);
echo "{$b} ({$a})"; // Harry James (POTTER)
?>
UPDv1:
In your current code, you might do just the same thing:
<?php
$lname = array_shift($name);
$fname = implode(' ', $name);
?>
I think you should take out the last name off the array first, then use a loop to concatenate the remaining names as fistname.
$fullname = array('fullname' => 'POTTER Harry James');
$res = implode("", $fullname);
$name = preg_split("/[\s,]+/", $res);
$lname = array_shift($name);
$fname = "";
foreach($name as $fnames)
$fname.= " ".$fnames;
$fullname = array('fullname' => 'POTTER Harry James');
$firstNames = strstr($fullname['fullname'], ' '); // $firstNames='Harry James'
This gets the string after the first space character.
This is a bit of an impossible task. If left to their own devices, users are going to put all sorts of stuff into a single field.
If you care about separating the first and last names of your users, you should ask for them separately, as there is no regex that can possibly determine the correct way to break up their name.
You could do
<?php
$fullname = array('fullname' => 'POTTER Harry James');
list($lname,$fname) = explode(" ", $fullname["fullname"],2);
echo $fname."<br>".$lname;
?>
This will work if the name contains 2 words or more. In case there are more than 2 words then anything except the first word will be considered as first name and first word will be considered as the last name.
I have some problems with the preg_replace.
I would change the mentions in a links but the name isn't a username.
So in the name there are spaces, i found a good solution but i don't know to do it.
Sostantially i would that preg_replace the words that are between # and ,
For example:
#John Doeh, #Jenna Diamond, #Sir Duck Norman
and replace to
VAL
How do I do it?
I think that you want it like:
John Doeh
For this try:
$myString="#John Doeh, #Jenna Diamond, #Sir Duck Norman";
foreach(explode(',',$myString) as $str)
{
if (preg_match("/\\s/", $str)) {
$val=str_replace("#","",trim($str));
echo "<a href='user.php?name=".$val."'>".$val."</a>";
// there are spaces
}
}
Based on my assumption you want to remove strings which start with #Some Name, in a text like: #Some Name, this is a message.
Then replace that to an href, like: First_Name
If that is the case then the following regex will do:
$str = '#First_Name, say something';
echo preg_replace ( '/#([[:alnum:]\-_ ]+),.*/', '$1', $str );
Will output:
First_Name
I also added support for numbers, underscores and dashes. Are those valid in a name aswell? Any other characters that are valid in a #User Name? Those are things that are important to know.
Two methods:
<?php
// preg_replace method
$string = '#John Doeh, #Jenna Diamond, #Sir Duck Norman';
$result = preg_replace('/#([\w\s]+),?/', '$1', $string);
echo $result . "<br>\n";
// explode method
$arr = explode(',', $string);
$result2 = '';
foreach($arr as $name){
$name = trim($name, '# ');
$result2 .= ''.$name.' ';
}
echo $result2;
?>
I have a text area which contains information as follows,
Secured places in the national squad respectively
Selected to the national team this year as well
Selected to the national team twice during his university career
Went to school at ABS
when user click the submit button, I want to get strings in each lines to php variables in submit page, something like this
$a = "Secured places in the national squad respectively";
$b = "Selected to the national team this year as well";
$c = "Selected to the national team twice during his university career";
$d = "Went to school at ABS";
can anyone please tell me how to do this?
If you don't care about sentences but rather line breaks, you should be able to break into an array based on that like this:
$posted_text = $_POST['text']; // or however you get the value into a string
$text_array = explode(PHP_EOL, $posted_text);
I think you looking for
explode('\n\r', $var)
where var is the value your ripping apart
Your best bet would be exploding the string via the newline character \n. Unfortunately, if the user didn't actually hit enter and the text has just rolled onto the next line, there won't be any newline characters to explode by.
Working example wihout breaking lines:
http://codepad.viper-7.com/OBiUXP
$words = explode(" ", str_replace("\n"," ",$text));
$sentences = Array();
$sentence = Array();
foreach($words as $word) {
$word = trim($word);
if(!$word) continue ;
$char1 = substr($word,0,1);
$char2 = substr($word,1,1);
if((strtoupper($char1) == $char1) && (strtolower($char2) == $char2)) {
if(count($sentence)) {
$sentences[] = join(" ", $sentence);
}
$sentence = Array();
}
$sentence[] = $word;
}
if(count($sentence)) {
$sentences[] = join(" ", $sentence);
}
Example Input: SMK SUNGAI PUNAI
My Code:
$school = 'SMK SUNGAI PUNAI';
echo ucwords(strtolower($school));
Unwanted Output: Smk Sungai Punai
Question
How to make the output SMK Sungai Punai which allows SMK to remain in ALL-CAPS.
Update.
The problem I have list of 10,000 school names. From PDF, I convert to mysql. I copied exactly from PDF the name of schools -- all in uppercase.
How can I implement conditional title-casing?
As far as I understand you want to have all school names with the first character of every word in uppercase and exclude some special words ($exceptions in my sample) from this processing.
You could do that like this:
function createSchoolName($school) {
$exceptions = array('SMK', 'PTS', 'SBP');
$result = "";
$words = explode(" ", $school);
foreach ($words as $word) {
if (in_array($word, $exceptions))
$result .= " ".$word;
else
$result .= " ".strtolower($word);
}
return trim(ucwords($result));
}
echo createSchoolName('SMK SUNGAI PUNAI');
This example would return SMK Sungai Punai as required by your question.
You can very simply create a pipe-delimited set of excluded words/acronyms, then use (*SKIP)(*FAIL) to prevent matching those whole words.
mb_convert_case() is an excellent function to call because it instantly provides TitleCasing and it is multibyte safe.
Code: (Demo)
$pipedExclusions = 'SMK|USA|AUS';
echo preg_replace_callback(
'~\b(?:(?:' . $pipedExclusions . ')(*SKIP)(*FAIL)|\p{Lu}+)\b~u',
fn($m) => mb_convert_case($m[0], MB_CASE_TITLE),
'SMK SUNGAI PUNAI'
);
// SMK Sungai Punai
There's no really good way to do it. In this case you can assume it's an abbreviation because it's only three letters long and contains no vowels. You can write a set of rules that look for abbreviations in the string and then uppercase them, but in some cases it'll be impossible... consider "BOB PLAYS TOO MUCH WOW."
You can use something like this:
<?php
$str = 'SMK SUNGAI PUNAI';
$str = strtolower($str);
$arr = explode(" ", $str);
$new_str = strtoupper($arr[0]). ' ' .ucfirst($arr[1]). ' ' .ucfirst($arr[2]);
echo '<p>'.$new_str.'</p>';
// Result: SMK Sungai Punai
?>