I want clear all commas from string and then put all words separated with comma into array.
For me it's easy to make it in the case i have this type of string:
word1,word2,word3,word4,word5,word6
I have juste to explode them and put them into array like this:
$words = "word1,word2,word3,word4,word5,word6";
$explode = explode(",", $words);
$array = array();
foreach($explode as $word) {
$array[] = $word;
}
And here come my need:
In the case i have this kind of string what is the approch ?
word1,,word2,,,word3,word4,,,,,,,,,,,,word5,,,,word6...
The number of commas between words undefined and can be up to 100 commas.
Let me know if u have good approch to this kind of string.
The array_filter function in PHP is used for "filtering" an array i.e. making a new array from the elements of an array that satisfy a condition.
By default if we do not pass any callback to array_filter, it removes all falsey and null values. We can send a callback function as a second parameter which returns true for elements that should stay and false for elements that should be removed.
$words = "word1,word2,word3,word4,word5,word6";
$words_arr = array_filter(explode(",", $words));
print_r($words_arr);
If there is whitespace between commas, then:
$words_arr = array_filter(explode(",", $words), function ($e) {
return strlen(trim($e)) > 0; // Only select those elements which have a length > 0 after trimming
});
strlen is for getting the string length
trim is for stripping whitespace from the beginning and end of a string
use preg_split
$explode = preg_split("/,+/", $words);
First use explode as you did to get all the values:
>>> $values = explode(',', 'word1,word2,,,,word3');
>>> print_r($values);
Array
(
[0] => word1
[1] => word2
[2] =>
[3] =>
[4] =>
[5] => word3
)
Use array_filter on the solution to filter out empty results:
>>> $non_empty_values = array_filter($values);
>>> print_r($non_empty_values);
Array
(
[0] => word1
[1] => word2
[5] => word3
)
Finally, to reset the array indices, use array_values:
>>> $results = array_values($non_empty_values);
>>> print_r($results)
Array
(
[0] => word1
[1] => word2
[2] => word3
)
Related
I need to merge data into an array, then count the array values.
$str = '"Cat","A","A","A","A"';
$abc = [
$str,
"A",
"Cat",
"Dog",
"A",
"Dog"
];
print_r(array_count_values($abc));
Result came out:
Array ( ["Cat","A","A","A","A"] => 1 [A] => 2 [Cat] => 1 [Dog] => 2 )
But I need like this way:
Array ( [A] => 6 [Cat] => 2 [Dog] => 2 )
This is because $str is a string and not an array. So this is added into the $abc array as one element.
You can convert in into an array with the explode function:
$str = '"Cat","A","A","A","A"';
$arr = explode(',', $str);
// So $arr is Array([0] => "Cat", [1] => "A", [2] => "A", [3] => "A", [4] => "A")
Then you need to remove the double quotes around each element.
I suggest to use the trim function, and the array_map, to apply it to each element:
$arr = array_map(function ($item) { return trim($item, '"'); }, $arr);
// $arr is Array([0] => Cat, [1] => A, [2] => A, [3] => A, [4] => A)
Then you can merge it with the rest of values:
$abc = array_merge($arr, array("A","Cat","Dog","A","Dog"));
print_r(array_count_values($abc));
// Should be Array ( [A] => 6 [Cat] => 2 [Dog] => 2 )
Well, then, don't put a string into an array and expect it to be treated as array values. Either modify the string to be an array, and merge the two arrays, or parse the string and add each value to the array.
For the latter approach, you can do something like:
$str = '"Cat","A","A","A","A"';
$abc = array("A","Cat","Dog","A","Dog");
$splitstr = explode(',',str_replace('"','',$str));
$finalarray = array_merge($abc,$splitstr);
print_r(array_count_values($finalarray));
Your logic is flawed, you should first create array properly
$str = '"Cat","A","A","A","A"';
$abc = array("A","Cat","Dog","A","Dog");
$splitstr = explode(',',str_replace('"','',$str));
$finalarray = array_merge($abc,$splitstr);
print_r(array_count_values($finalarray));
Now you will get the desired result.
Because your quote-wrapped, comma-delimited string closely resembles a json string, I reckon it will be most direct/performant to just wrap the whole string in square braces, then json_decode it and spread it into the array (so that elements are injected into the array one at a time).
Code: (Demo)
$str = '"Cat","A","A","A","A"';
$abc = [
...json_decode("[$str]"),
"A",
"Cat",
"Dog",
"A",
"Dog"
];
print_r(array_count_values($abc));
you put first element as string completely. make it separate
$str = '"Cat","A","A","A","A"';
$abc=array( "Cat","A","A","A","A", "A","Cat","Dog","A","Dog");
print_r(array_count_values($abc));
Or merge array
$arr1 = ["Cat","A","A","A","A"];
$abc=array_merge( $arr1,["A","Cat","Dog","A","Dog"]);
print_r(array_count_values($abc));
Demo
You are using array_count_values to count all the values of the $abc array. However, $str is a string and not an array, but an element of the $abc array.
The simplest solutions is to convert $str into an array by removing " double quotes (with str_replace method) and splitting substrings using , as a delimiter (with explode method). This can be done just by adding a single line as shown in this snippet:
$str = '"Cat","A","A","A","A"';
// Converts $str into an array of strings
$str_array = explode(',',str_replace('"','',$str));
$abc = array_merge($str_array, array("A","Cat","Dog","A","Dog"));
print_r(array_count_values($abc));
You can see the execution of this script in this link.
According to the PHP manual, you can use array_merge ( array $array1 [, array $... ] )
example:
$str = '"Cat","A","A","A","A"';
$abc=array_merge($str, array("A","Cat","Dog","A","Dog"));
print_r(array_count_values($abc));
After instructing clients to input only
number comma number comma number
(no set length, but generally < 10), the results of their input have been, erm, unpredictable.
Given the following example input:
3,6 ,bannana,5,,*,
How could I most simply, and reliably end up with:
3,6,5
So far I am trying a combination:
$test= trim($test,","); //Remove any leading or trailing commas
$test= preg_replace('/\s+/', '', $test);; //Remove any whitespace
$test= preg_replace("/[^0-9]/", ",", $test); //Replace any non-number with a comma
But before I keep throwing things at it...is there an elegant way, probably from a regex boffin!
In a purely abstract sense this is what I'd do:
$test = array_filter(array_map('trim',explode(",",$test)),'is_numeric')
Example:
http://sandbox.onlinephpfunctions.com/code/753f4a833e8ff07cd9c7bd780708f7aafd20d01d
<?php
$str = '3,6 ,bannana,5,,*,';
$str = explode(',', $str);
$newArray = array_map(function($val){
return is_numeric(trim($val)) ? trim($val) : '';
}, $str);
print_r(array_filter($newArray)); // <-- this will give you array
echo implode(',',array_filter($newArray)); // <--- this give you string
?>
Here's an example using regex,
$string = '3,6 ,bannana,5,-6,*,';
preg_match_all('#(-?[0-9]+)#',$string,$matches);
print_r($matches);
will output
Array
(
[0] => Array
(
[0] => 3
[1] => 6
[2] => 5
[3] => -6
)
[1] => Array
(
[0] => 3
[1] => 6
[2] => 5
[3] => -6
)
)
Use $matches[0] and you should be on your way.
If you don't need negative numbers just remove the first bit in the in the regex rule.
I have a string which contains numbers separated by commas. It may or may not have a space in between the numbers and a comma in the end. I want to convert it into an array, that I can do using following code:
$string = '1, 2,3,';
$array = explode(',', $string);
However the additional irregular spaces gets in the array values and the last comma causes an empty index (see image below).
How can I remove that so that I get only clean values without spaces and last empty index in the array?
Simply use array_map, array_filter and explode like as
$string = '1, 2,3,';
print_r(array_map('trim',array_filter(explode(',',$string))));
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Explanation:
Firstly I've split string into an array using explode function of PHP
print_r(explode(',',$string));
which results into
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] =>
)
So we need to remove those null values using array_filter like as
print_r(array_filter(explode(',',$string)));
which results into
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Now the final part need to remove that (extra space) from the values using array_map along with trim
print_r(array_map('trim',array_filter(explode(',',$string))));
SO finally we have achieved the part what we're seeking for i.e.
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Demo
The simple solution would be to use str_replace on the original string and also remove the last comma if it exists with a rtrim so you dont get an empty occurance at the end of the array.
$string = '1, 2,3,';
$string = rtrim($string, ',');
$string = str_replace(' ', '', $string);
$array = explode(',', $string);
print_r($array);
RESULT:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
First perform following on the string -
$string = str_replace(' ', '', $string);
Then use explode.
$string = '1, 2,3,';
$array = explode(',', $string);
$array = array_filter(array_map('trim', $array));
print_r($array);
array_map is a very useful function that allows you to apply a method to every element in an array, in this case trim.
array_filter will then handle the empty final element for you.
This will trim each value and remove empty ones in one operation
$array = array_filter( array_map( 'trim', explode( ',', $string ) ) );
$str="a,b,c,d-e,f,g,h"
I am trying to extract the strings from $str that are separated "," and are before "-" in one array and the strings separated by "," and are after "-" in second array. So that $arr1=array(a,b,c,d); and $arr2=array(e,f,g,h);. I am just using $str as an example and generally I want this to work for any string of the same form i.e. $str=s1,s2,s3,s4,s5,....-r1,r2,t3....
NOTE: If $str doesn't have "-" then $arr2 vanishes and $arr1 contains an array of the elements separated by ',' in $str.
This is what I tried
preg_match_all('~(^|.*,)(.*)(,.*|\-|$)~', $str, $arr1);
preg_match_all('~(-|.*,)(.*)(,.*|$)~', $str, $arr2);
However each array comes with one element that contains the string str.
Does anyone know why this is not working.
All of your regex patterns are not optimal and it seems the task is easier to solve with explode and array_map:
array_map() returns an array containing all the elements of array1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()
$str="a,b,c,d-e,f,g,h";
$ex = array_map(function ($s) {
return explode(",", $s);
}, explode("-", $str));
print_r($ex);
See IDEONE demo
Results:
Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)
[1] => Array
(
[0] => e
[1] => f
[2] => g
[3] => h
)
)
^(.*?(?=-|$))|(?<=-)(.*$)
You can use this to get 2 arrays.See demo.
https://regex101.com/r/vV1wW6/19
Your regex is not working as you have used greedy modifier..*, will stop at the last instance of ,
EDIT:
Use this is you want string after - to be in second group.
^(.*?(?=-|$))(?:-(.*$))?
https://regex101.com/r/vV1wW6/20
You can simply use preg_match to check does your string contains - if yes than can simply use array_walk like as
$str = 'a,b,c,d-e,f,g,h';
$result = [];
if(preg_match('/[-]/', $str)){
array_walk(explode('-',$str),function($v,$k)use(&$result){
$result[] = explode(',',$v);
});
}else{
array_walk(explode(',',$str),function($v,$k)use(&$result){
$result[] = $v;
});
}
print_r($result);
Without regex (the most reasonable way):
$str="a,b,c,d-e,f,g,h";
list($arr1, $arr2) = explode('-', $str);
$arr1 = explode(',', $arr1);
if ($arr2)
$arr2 = explode(',', $arr2);
else
unset($arr2);
With regex (for the challenge):
if (preg_match_all('~(?:(?!\G)|\A)([^-,]+)|-?([^,]+),?~', $str, $m)) {
$arr1 = array_filter($m[1]);
if (!$arr2 = array_filter($m[2]))
unset($arr2);
}
I have a multidimensional array. They keys of the separate arrays are text. I would like to know how to match the key with part of a string that's from looped SELECT data.
Example of Array
Array ( [Volvo] => Array ( [0] => )
[Ford] => Array ( [0] => )
[Seat] => Array ( [0] => ) )
So from this array $cars, how would I be able to match data coming from my SELECT query
Select Output echo $row['car'];
Volvo, Mercedes, Lexus
What I'm after
if the key of one of my arrays matches part of the string from my select query, so as the example says above Volvo would match, then do something. That something for me is adding more data in that array.
I have tried variations of in_array, array_search and array_filter but have not found a solution that works for me.
Example of the reverse of what i was doing through a foreach loop
$searchword = $array_element;
$result = array_filter($cars, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); });
taken from: Search for PHP array element containing string
This should work for you:
First I used preg_split() to split your search string (Volvo, Mercedes, Lexus) into an array.
The regex:
/\s*,\s*/
Simply means this:
\s* match any white space character [\r\n\t\f ]
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
, matches the character , literally
\s* match any white space character [\r\n\t\f ]
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
This makes sure we don't have spaces in the search words from your string. So with this we will end up with an array like this:
Array
(
[0] => Volvo
[1] => Mercedes
[2] => Lexus
)
After that I just take the array_intersect_key() from your array and the search array, which we just created.
Code:
<?php
$arr = preg_split("/\s*,\s*/", $row["car"], -1, PREG_SPLIT_NO_EMPTY);
if(($intersect = array_intersect_key($cars, array_flip($arr)))) {
echo "Do stuff!";
print_r($intersect);
} else {
echo "Drink a cup of tea";
}
?>
output:
Array
(
[Volvo] => Array
(
[0] =>
)
)
There are many ways to achieve your goal. I would use function explode() to split the data retrieved from the database ($row['car']) into pieces and trim() to be sure the identified pieces do not have padding spaces:
$brands = array_map('trim', explode(',', $row['car']));
Now, print_r($brands) should reveal an array whose values are candidate keys in your example array (called $example below).
Next it depends on what you want to match and how you want to process the matches.
A simple identification can be done using array_intersect() with $brands and the keys of the example array (see function array_keys()).
$common = array_intersect($brands, array_keys($example));
foreach ($common as $key) {
// Do something with $example[$key]
}
Or you can iterate directly over $brands and check if the value is a key in $example:
foreach ($brands as $key) {
if (array_key_exists($key, $example)) {
// Do something with $example[$key]
}
}
You can use isset($example[$key]) as well, instead of array_key_exists($key, $example]).
Try using PHP stripos, it's simple and effective:
Base data:
$array = Array ( [Volvo] => Array ( [0] => )
[Ford] => Array ( [0] => )
[Seat] => Array ( [0] => ) )
;
SQL data (string or array):
$row['car']; // string
$row //array of all SQL columns output
Foreach with stripos:
foreach($array as $rowKey=>$rowArray){
$rowKey = trim($rowKey);
foreach($row as $sqlRow=>$sqlArray){
$sqlRow = trim($sqlRow);
if (stripos($rowKey,$sqlRow) !== false){
///values are the same in this key in the array and in the SQL output
}
}
unset($sqlRow,$sqlArray);
}
unset($rowKey,$rowArray);
This may not be the most efficient but should give you the result you want