concatenating array elements between first and last dynamically in php - php

i have searched on the Internet but i couldn't find a solution, i have got a string which contain names(two, three,..) of a staff.
i want to extract from this string the first name, middle names and last name
sample string
$name = "Michael O. A. Ndanshau";
I am using explode function to get the names
$exp =explode(" ",$name);
print_r($exp);
array output
Array
(
[0] => Michael
[1] => O.
[2] => A.
[3] => Ndanshau
)
from above array i can get the first name and last name
$fname = $exp[0];
$lname = end($exp);
am not sure how to get the middle name as it may be dynamic.
my target is to concatenate what is between the first element and the last as the middle name
if a have n elements in the array
$middename = $exp[1]+..$exp[n-1];
any help please?

Get the first element of the array to get the first name and last element to get the last name. Get everything between for the middle name:
$firstname = $parts[0];
$middlename = implode(array_slice($parts, 1, -1));
$lastname = end($parts);
var_dump($firstname, $middlename, $lastname);
Output:
string(7) "Michael"
string(4) "O.A."
string(8) "Ndanshau"
Demo

if(count($arr)>2) {
$middleName = implode(' ',array_slice($arr,1,count($arr)-2));
}
else {
$middleName = '';
}

Maybe something like this. array_shift and array_pop modify the array so all that is left is the element(s) for the middle name:
$fname = array_shift($exp);
$lname = array_pop($exp);
middlename = implode(' ', $exp);
But you might want to check to make sure there are more than 2 elements up front, or at least 1 remaining:
$fname = array_shift($exp);
$lname = array_pop($exp);
if(count($exp) >= 1) {
middlename = implode(' ', $exp);
}
Or something similar.

Related

PHP Crushing/Explode text

I have a one input that is used for a "Name, Surname and Family name". But I want if user enter more than 3 names, all after 3(4,5,6...) to be like family. But if you submit 2 names the Family name must be "0".
Here is my code:
<form method="POST" action="getNames.php">
Names: <input type="text" name="names" />
<input type="submit" name="submit" />
</form>
<?php
$names = $_POST['names'];
// some action here to get names
$firstName = ""; // Get first name
$surName = ""; // Get Sur name
$familyName = ""; // Get family name
?>
I will be very glad if someone help me. Thanks!
This code will output an array of familly, if an input is missing, it will be replaced with a 0.
PHP
<?php
$_POST['names'] = 'sofiene, totose, tata, titi';
$names = explode(',', $_POST['names']);
$familly = [];
for ($i = 0; $i < count($names); $i+=3) {
$familly[$i] = [
'firstName' => (isset($names[$i])) ? $names[$i] : 0,
'surName' => (isset($names[$i + 1])) ? $names[$i + 1] : 0,
'familyName' => (isset($names[$i + 2])) ? $names[$i + 2] : 0
];
}
var_dump($familly);
?>
EvalIn
You can use explode with a space, and use array_filter on that to remove blanks, as user may input two spaces.
There after you can use array_shift which return you a value from top of an array.
and later check if array isn't empty, then use implode with spaces otherwise set $familyName to 0
<?php
$names = 'John Doe';
$arrNames = array_filter(explode(' ', $names));
echo $firstName = array_shift($arrNames) . PHP_EOL;
echo $surName = array_shift($arrNames) . PHP_EOL;
echo $familyName = empty($arrNames) ? '0' : implode(' ', $arrNames);
This what your looking for?
$_POST['names'] = ' Arthur Ignatius Conan Doyle ';
$names = trim(preg_replace('/\s+/', ' ', $_POST['names']));
$parts = explode(' ',$names , 3);
list($firstNamm, $surName, $familyName) = array_replace(array_fill(0,3,''), $parts );
Explanation,
preg_replace('/\s+/', ' ', $_POST['names']) is used to reduce multiple spaces down to a single whitespace.
from
' Arthur Ignatius Conan Doyle '
to
' Arthur Ignatius Conan Doyle '
trim() is used to remove whitespace from the beginning and end of a string, you can provide a second argument if you wish to remove other characters.
which now gives us
'Arthur Ignatius Conan Doyle'
explode() splits a string into an array when given a delimiter (" "), the 3rd arguments let you set the maximum number of parts to split the string into.
as the string may not have 3 parts its possible that an empty array is returned.
array_fill(0,3,'') creates an array with three elements all set to an empty string.
array_replace(array_fill(0,3,''), $parts ); returns the array but with values replaced with any values provided by the $parts array.
This array is passed to the list construct which populates a list of variables with the values of each array element.

How Can I Extract the stringlength higher word in an array?

In the first time, I'm sorry for my disastrous english.
After three days trying to solve this, i give up.
Giving this array:
$names = array ( "James Walter Case", "Benjamin Wallace Pinkman", "Billy Elliot Newson" )
I have to extract the full name of the higher first stringlength word of each full name.
In this case, considering this condition Benjamin will be the higher name. Once
this name extracted, I have to print the full name.
Any ideas ? Thanks
How about this?
$names = array ( "James Walter Case", "Benjamin Wallace Pinkman", "Billy Elliot Newson" );
if (count($names) > 0)
{
$higher_score = 0;
foreach ($names as $name_key => $name_value)
{
$name_array = explode(" ", $name_value);
// echo("<br><b>name_array -></b><pre><font FACE='arial' size='-1'>"); print_r($name_array); echo("</font></pre><br>");
$first_name = $name_array[0];
// echo "first_name -> ".$first_name."<br>";
$score = strlen($first_name);
// echo "score -> ".$score."<br>";
if ($score > $higher_score)
{
$higher_score = $score;
$winner_key = $name_key; }
}
reset($names);
}
echo("longest first name is ".$names[$winner_key]." with ".$higher_score." letters.");
As said before, you can use array_map to get all the lenghts of the first strings, and then get the name based on the key of that value.
$names = array ( "James Walter Case", "Benjamin Wallace Pinkman", "Billy Elliot Newson" );
$x = array_map(
function ($a) {
$x = explode (" ", $a); // split the string
return strlen($x[0]); // get the first name
}
, $names);
$maxs = array_keys($x, max($x)); // get the max values (may have equals)
echo $names[$maxs[0]]; // get the first max
-- EDIT
Actually, there is a better way of doing this, considering this case. You can simply order the array by the lenght of the first names, and then get the first key:
usort($names,
function ($a, $b) {
$aa = explode(" ", $a); // split full name
$bb = explode(" ", $b); // split full name
if (strlen($aa[0]) > strlen($bb[0])){
return 0; // if a > b, return 0
} else {
return 1; // else return 1
}
}
);
echo $names[0]; // get top element
Allow me to provide a handmade solution.
<?php
$maxLength = 0;
$fullName = "";
$parts = array();
foreach($names as $name){
/* Exploding the name into parts.
* For instance, "James Walter Case" results in the following array :
* array("James", "Walter", "Case") */
$parts = explode(' ', $name);
if(strlen($parts[0]) > $maxLength){ // Compare first length to the maximum.
$maxLength = strlen($parts[0]);
$fullName = $name;
}
}
echo "Longest first name belongs to " . $fullName . " (" . $maxLength . " character(s))";
?>
Basically, we iterate over the array, split each name into parts (delimited by spaces), and try to find the maximum length among first parts of names ($parts[0]). This is basically a maximum search algorithm.
There may be better ways with PHP array_* functions, but well, this one gets pretty self-explanatory.
You can try something like..
$maxWordLength=0;
$maxWordIndex=null;
foreach ($names as $index=>$name){
$firstName=first(explode(' ',$name));
if (strlen($firstName)>maxWordLength){
$maxWordLength=strlen($firstName);
$maxWordIndex=$index;
}
}
if ($maxWordIndex){
echo $names[$maxWordIndex];
}

PHP problems parsing a bible book string

I hope you can help me.
I have a string like the following
Luke 1:26-38
And I would like to be able to break it up into tokens or individual variables so that I can use the variables in an SQL query.
I've tried using explode, however I've only been able to make it explode on one character such as : or -
My string has : and - and also a space between the name and the first number.
My goal is to have:
$name = Luke;
$book = 1;
$from = 26;
$to = 38;
Is anyone able to help please.
Many thanks
You can do that with a simple string scanning (Demo):
$r = sscanf("Luke 1:26-38", "%s %d:%d-%d", $name, $book, $from, $to);
The varibales then contain the information. %s represents a string (without spaces), %d a decimal. See sscanf.
To make this "bible safe", it needs some additional modifications:
$r = sscanf($string, "%[ a-zA-Z] %d:%d-%d", $name, $book, $from, $to);
$name = trim($name);
(Second demo).
list( $name, $book, $from, $to ) = preg_split( '/[ :-]/', 'Luke 1:26-38' );
echo $name; //"Luke"
/* Split results in an Array
(
[0] => Luke
[1] => 1
[2] => 26
[3] => 38
)
*/
$string = "Luke 1:26-38";
preg_match('#^(\w+)\s(\d+):(\d+)-(\d+)$#', $string, $result);
print_r($result);
regex is hard to configure for this because of the multiple configurations of bible book names, chapter and verse num. Because some books begin with a number and some books have multiple spaces in the book names.
I came up with this for building a sql query, it works for these passage search types..
(John), (John 3), (Joh 3:16), (1 Thes 1:1)
Book names can be 3 letter abbreviations.
Does unlimited individual word search and exact phrase.
$string = $_GET['sstring'];
$type = $_GET['stype'];
switch ($type){
case "passage":
$book = "";
$chap = "";
$stringarray = explode(':', $string); // Split string at verse refrence/s, if exist.
$vref = $stringarray[1];
$vrefsplit = explode('-', $vref);// Split verse refrence range, if exist.
$minv = $vrefsplit[0];
$maxv = $vrefsplit[1]; // Assign min/max verses.
$bc = explode(" ", $stringarray[0]); // Split book string into array with space as delimiter.
if(is_numeric($bc[count($bc)-1])){ // If last book array element is numeric?
$chap = array_pop($bc); // Remove it from array and assign it to chapter.
$book = implode(" ", $bc); // Put remaining elemts back into string and assign to book.
}else{
$book = implode(" ", $bc); // Else book array is just book, convert back to string.
}
// Build the sql query.
$query_rs1 = "SELECT * FROM kjvbible WHERE bookname LIKE '$book%'";
if($chap != ""){
$query_rs1.= " AND chapternum='$chap'";
}
if($maxv != ""){
$query_rs1.= " AND versenum BETWEEN '$minv' AND '$maxv'";
}else if($minv != ""){
$query_rs1.= " AND versenum='$minv'";
}
break;
case "words":
$stringarray = explode(" ", $string); // Split string into array.<br />
// Build the sql query.
$query_rs1 = "SELECT * FROM kjvbible WHERE versetext REGEXP '[[:<:]]". $stringarray[0] ."[[:>:]]'";
if(count($stringarray)>1){
for($i=1;$i<count($stringarray);$i++){
$query_rs1.= " AND versetext REGEXP '[[:<:]]". $stringarray[$i] ."[[:>:]]'";
}
}
break;
case "xphrase":
// Build the sql query.
$query_rs1 = "SELECT * FROM kjvbible WHERE versetext REGEXP '[[:<:]]". $string ."[[:>:]]'";
break;
default :
break;
}

php string tokenizing

Wondering if I could get some advice on tokenizing a string in php since Im relatively new to the language.
I have this:
$full_name = "John Smith"
I want to use a string function that will extract the first name and last name into indices of an array.
$arr[0] = "John"
$arr[1] = "Smith"
However, the function should also be able to handle the situation:
$full_name = "John Roberts-Smith II"
$arr[0] = "John"
$arr[1] = "Roberts-Smith II"
or
$full_name = "John"
$arr[0] = ""
$arr[1] = "John"
any suggestions on where to begin?
Use explode() with the optional limit param:
$full_name = "John Roberts-Smith II"
// Explode at most 2 elements
$arr = explode(' ', $full_name, 2);
// Your values:
$arr[0] = "John"
$arr[1] = "Roberts-Smith II"
Your last case is special though, placing the first name into the second array element. That requires special handling:
// If the name contains no whitespace,
// put the whole thing in the second array element.
if (!strpos($full_name, ' ')) {
$arr[0] = '';
$arr[1] = $full_name;
}
So a complete function:
function split_name($name) {
if (!strpos($name, ' ')) {
$arr = array();
$arr[0] = '';
$arr[1] = $name;
}
else $arr = explode(' ', $name, 2);
return $arr;
}
You should explode() function for this purpose.
$name_splitted = explode(" ", "John Smith", 2);
echo $name_splitted[0]; // John
echo $name_splitted[1]; // Smith
From the documentation -
array explode ( string $delimiter , string $string [, int $limit ] )
Returns an array of strings, each of which is a substring of "string" formed by splitting it on boundaries formed by the string "delimiter". If "limit" is set and positive, the returned array will contain a maximum of "limit" elements with the last element containing the rest of string. If the "limit" parameter is negative, all components except the last -"limit" are returned. If the "limit" parameter is zero, then this is treated as 1.

PHP: Separate one field in two

As many recommend me to separate firstname and lastname instead of "full_name" with everything in, how can I separate them to each variables, so if for you example type in the field: "Dude Jackson" then "Dude" gets in $firstname and Jackson in the $lastname.
It's impossible to do with 100% accuracy, since the first/last name contains more information than a single "full name". (A full name can include middle names, initials, titles and more, in many different orders.)
If you just need a quick fix for a legacy database, it might be OK to split by the first space.
Assuming first name always comes first and there's no middle name:
list($firstname, $lastname) = explode(' ', $full_name);
This simply explodes $full_name into an array containing two strings if they're separated by only one space, and maps them to the first and last name variables respectively.
You can do:
list($first_name,$last_name) = explode(' ',$full_name);
This assumes that you full name contains first name and last name separated by single space.
EDIT:
In case the lastname is not present, the above method give a warning of undefined offset. To overcome this you can use the alternative method of:
if(preg_match('/^(\S*)\s*(\S*)$/',$full_name,$m)) {
$first_name = $m[1];
$last_name = $m[2];
}
$full_name = "Dude Jackson";
$a = explode($full_name, " ");
$firstname = $a[0];
$lastname = $a[1];
you would need to explode the value into its parts using a space as the separator
http://php.net/manual/en/function.explode.php
I am no PHP programmer, but for a quick fix, without data loss,
$full_name = "Dude Jackson";
$a = explode($full_name, " ");
$firstname = $a[0];
$count = 1;
$lastname = "";
do {
$lastname .= $a[$count]." ";
$count++;
} while($count<count($a));
$lastname = trim($lastname);
This should save all remaining part of name in $lastname, should be helpful for names like "Roelof van der Merwe". Also you can throw in checks for $full_name as first name only, without last name.
This is the code/solution
$full_name = "Dude Jackson";
$a = explode($full_name, " ",1);
if(count($a) == 2)
{
$firstname = $a[0];
$lastname = $a[1];
}
if(count($a) < 2)
{
$firstname = $full_name;
$lastname = " ";
}

Categories