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);
Related
I have this sentence:
$newalt="My name is Marie";
I want to include a page if marie or josh is found:
$words = array("marie", "josh");
$url_string = explode(" ", $newalt);
if(!in_array($url_string, $words)){
echo "marie or josh are not in array";
}
the problem is, when I run this php it shows "marie or josh are not in array" and marie is the array (or should be).
What is wrong?
The solution using array_intersect and array_map functions:
$newalt = "My name is Marie";
$words = ["marie", "josh"];
$url_string = explode(" ", $newalt);
if (empty(array_intersect($words, array_map("strtolower", $url_string)))) {
echo "marie or josh are not in array";
}
http://php.net/manual/en/function.array-intersect.php
You have 2 errors. First, in_array() is case-sensitive. You need to make the haystack all lowercase first. Second, in_array() does not accept an array as the needle. To overcome this, you can use something like array_diff():
$newalt="My name is Marie";
$words = array("marie", "josh");
$url_string = explode(" ", strtolower($newalt));
if(count(array_diff($words, $url_string) == count($words)){
echo "marie or josh are not in array";
}
The first parameter of the in_array function is a array. Your $words array is filled with strings and not arrays.
Maybe try something like this:
$words = array("marie", "josh");
$urlStrings = explode(" ", $newalt);
foreach ($urlStrings as $urlString) {
if(!in_array($urlString, $words)){
echo "marie or josh are not in array";
}
}
You wrongly used in_array(), in array to check the first parameter is in the second parameter.
in_array(strtolower($words[0]), array_map('strtolower', $url_string)) && in_array(strtolower($words[1]), array_map('strtolower', $url_string))
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 multiple different db strings, one for example is:
"Apples,Apples,Apples,Oranges,Apples,Oranges"
I want to represent each string dynamically as:
"I have Apples and Oranges. There are 6 in total."
Another string might be:
"Apples,Apples,Apples,Apples";
Should say:
"I have Apples. There are 4 in total."
How would I script this in PHP? Ty for help!
<?php
$str = 'Apples,Apples,Apples,Oranges,Apples,Oranges';
$arr = explode(',', $str);
echo 'I have '.implode(' and ', array_unique($arr))
. '. There are '.count($arr).' in total.';
This should be self explanatory but for reference see: explode, implode & array_unique
I made this test:
<?php
$data = "Apples,Apples,Apples,Oranges,Apples,Oranges";
$array = explode(",",$data); //array of elements
$count = count($array); //How many elements
$arr_unique = array_unique($array); //array of unique elements
echo "I have ".implode(" and ", $arr_unique). ". There are ".$count." in total.";
//var_dump($arr_unique); //For test
?>
PS: Check the fiddle: http://phpfiddle.org/main/code/3u4-e5v
I'd like to explode a string, but have the resulting array have specific strings as keys rather than integers:
ie. if I had a string "Joe Bloggs", Id' like to explode it so that I had an associative array like:
$arr['first_name'] = "Joe";
$arr['last_name'] = "Bloggs";
at the moment, I can do:
$str = "Joe Bloggs";
$arr['first_name'] = explode(" ", $str)[0];
$arr['last_name'] = explode(" ", $str)[1];
which is inefficient, because I have to call explode twice.
Or I can do:
$str = "Joe Bloggs";
$arr = explode(" ", $str);
$arr['first_name'] = $arr[0];
$arr['last_name'] = $arr[1];
but I wonder if there is any more direct method.
Many thanks.
I would use array_combine like so:
$fields = array ( 'first_name', 'last_name' );
$arr = array_combine ( $fields, explode ( " ", $str ) );
EDIT: I would also pick this over using list() since it allows you to add fields should you require without making the list() call unnecessarily long.
You can make use of list PHP Manual (Demo):
$str = "Joe Bloggs";
list($arr['first_name'], $arr['last_name']) = explode(" ", $str);
$arr then is:
Array
(
[last_name] => Bloggs
[first_name] => Joe
)
You cannot do explode(" ", $str)[0] in PHP <= 5.3.
However, you can do this:
list($arr['first_name'], $arr['last_name']) = explode(" ", $str);
I have a string such as:
Crosby Bing, Gretzky Wayne, Clemente Roberto
I would like to have the string converted to an array so it looks like:
LName[0]=>Crosby
FName[0]=>Bing,
LName[1]=>Gretzky
FName[1]=>Wayne,
LName[2]=>Clemente
FName[2]=>Roberto
I am terrible with arrays and string manipulation and have done many searches on the web but can't locate the appropriate solution.
I look forward to your response!
$nameString = 'Crosby Bing, Gretzky Wayne, Clemente Roberto';
$names = array_map('trim', explode(',', $nameString));
foreach ($names as &$name) {
$name = explode(' ', $name, 2);
}
Its slightly different from what you want. Its an array of arrays, where the inner arrays has 2 values with the first one the first and the second value is the second (and any further) name. It should not be difficult to convert it into your structure, if even required.
echo $name[0][0]; // Crosby
echo $name[0][1]; // Bing
Kevin Peno suggest something like this in the comments below
$nameString = 'Crosby Bing, Gretzky Wayne, Clemente Roberto';
foreach (explode(',',$nameString) as &$name) {
$name = explode(' ', trim($name), 2);
}
However, they both are semantic equivalent and as long as there are not 1M names in the string (which will also consumes "1M * average-string-length Byte" of memory), I dont think anyone may realise any performance difference.
Try this out:
<?php
$LName = array();
$FName = array();
list($LName[0],$FName[0],$LName[1],$FName[1],$LName[2],$FName[2]) =
explode(" ","Crosby Bing, Gretzky Wayne, Clemente Roberto");
print_r($LName);
print_r($FName);
?>
demo: http://codepad.org/g4YnwKxW
Or if your list is dynamic:
<?php
$LName = array();
$FName = array();
$fullNames =
explode(", ","Crosby Bing, Gretzky Wayne, Clemente Roberto");
foreach($fullNames as $full){
list($LName[], $FName[]) = explode(" ", $full);
}
print_r($LName);
print_r($FName);
?>
demo: http://codepad.org/WMIx9mJD
Done in one line!
preg_match_all('/(\w+) (\w+)(?:, )?/', "Crosby Bing, Gretzky Wayne, Clemente Roberto", $a);
/*
$fName = $a[1];
$lName = $a[2];
*/
I think explode() can be useful.
Example:
Things used:
explode()
var_dump()
$name = 'Crosby Bing';
$splittedName = explode(' ', $name);
var_dump($splittedName);
Should return:
[0] => 'Crosby',
[1] => 'Bing'
And splitting list of names is just simple loop:
Things used:
explode()
foreach
reference
$names = 'Crosby Bing, Gretzky Wayne, Clemente Roberto';
$namesArray = explode(',', $names);
foreach($names as &$name)
{
$name = explode(' ', trim($name));
}
And simple function:
Things used:
explode()
Function creation
count()
array_slice()
function GetNames($name)
{
$names = explode(' ', $name);
$namesCount = count($names);
$data = array();
$data['Names'] = array_slice($names, 0, $namesCount - 2);
$data['Surname'] = $names[$namesCount - 1];
return $data;
}
You need to do two operations. First to split the initial string into an array of names and then work through that array and split each name into firstname and lastname.
The following code shows that but works only under the premise that a full name contains only of a firstname and lastname and both are sperated by a single space.
$allNames = 'Crosby Bing, Gretzky Wayne, Clemente Roberto'; // your string
$names = explode(', ', $allNames); // create an array with all names
$LName = $FName = array(); // initialize your result arrays
foreach($names as $name) {
list($firstName, lastName) = explode(' ', $name, 2); // split each name apart
$FName[] = $firstName; // add first name to result array
$LName[] = $lastName; // add last name to result array
}
Explode is your friend here ;)
You could use the explode function, like so:
$names_string = "Crosby Bing, Gretzky Wayne, Clemente Roberto";
$names = explode(",", $names_string);
echo $names[0]; // displays Crosby Bing
echo $names[1]; // displays Gretzky Wayne
Demo
http://codepad.org/P4vSIgKP
Code
$str = 'Crosby Bing, Gretzky Wayne, Clemente Roberto';
$arr1=explode(',', $str);
foreach ($arr1 as $item){
$arr2 = explode(' ', trim($item));
$lname[]=$arr2[0];
$fname[]=$arr2[1];
}
print_r($lname);
print_r($fname);
Result
Array
(
[0] => Crosby
[1] => Gretzky
[2] => Clemente
)
Array
(
[0] => Bing
[1] => Wayne
[2] => Roberto