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 ) ) );
Related
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 like below:
$arrayString = "[Orange,Apple,Grape]";
How can I convert this into an Array?
I'm not a fan of str_replace replacing square brackets because they might be replaced in the array string, so let's trim them instead, and explode the list on the commas. Given your sample above, this will produce an array of strings.
$arrayString = "[Orange,Apple,Grape]";
print_r( explode(",", trim($arrayString, "][")) );
Results:
Array
(
[0] => Orange
[1] => Apple
[2] => Grape
)
Note: If you have escaped commas, then this won't work.
Something like this perhaps should do it.
$arrayString = "[Orange,Apple,Grape]";
$array=explode( ',', str_replace( array('"','[',']'), '', $arrayString ) );
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
)
$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 this array and want to remove all # char from first of all values of it:
$array = ('#test' , '#test1' , '#test2' ... etc);
I know How I can to remove all special chars with "Foreach" or "for" or any function
But I need to find out is there any way to remove a special character from all values of an array with one or maximum two line in PHP
Kind Regards
Simple do an array_walk
<?php
$array = ['#test' , '#test1' , '#test2','nohash','#test4'];
array_walk($array,function (&$v){ if(strpos($v,'#')!==false){ $v = str_replace('#','',$v);}},$array);
print_r($array);
OUTPUT :
Array
(
[0] => test
[1] => test1
[2] => test2
[3] => nohash
[4] => test4
)
Much simpler if you don't need to test for the first character:
$array = str_replace('#', '', $array);