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 ) );
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 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 ) ) );
I am trying to get some specific values out of the following string:
{"car":"Toyota"{"car":"honda"{"car":"BMW{"car":"Hyundai"
I want to get 'Toyota' out of that. The string is randomly generated, so it could be Benz or Pontiac.
Not really sure what this crazy string is from, but if you've accurately shown the format, this will extract the strings you're after:
$string = '{"car":"Toyota"{"car":"honda"{"car":"BMW{"car":"Hyundai"';
$string = array_filter(
explode(',',
preg_replace(
array('/"/', '/{/', '/:/', '"car"'),
array('', ',', '', ''),
$string
)
)
);
print_r($string);
// Output: Array ( [1] => Toyota [2] => honda [3] => BMW [4] => Hyundai )
... if, instead, this is just a horrible typeo and this is supposed to be JSON, use json_decode:
$string = '[{"car":"Toyota"},{"car":"honda"},{"car":"BMW"},{"car":"Hyundai"}]'; // <-- valid JSON
$data = json_decode($string, true);
print_r($data);
// Output: Array ( [0] => Array ( [car] => Toyota ) [1] => Array ( [car] => honda ) [2] => Array ( [car] => BMW ) [3] => Array ( [car] => Hyundai ) )
Documentation
preg_replace - http://php.net/manual/en/function.preg-replace.php
array_filter - http://php.net/manual/en/function.array-filter.php
explode - http://php.net/manual/en/function.explode.php
json_decode - http://php.net/manual/en/function.json-decode.php
Although this looks like a corrupt piece of JSON, I would say you can get the first car with explode().
$string = '{"car":"Toyota"{"car":"honda"{"car":"BMW{"car":"Hyundai"';
$string = explode("{", $string);
$firstcar = $string[1]; //your string starts with {, so $string[0] would be empty
$firstcar = explode(":", $firstcar);
$caryouarelookingfor = $firstcar[1]; // [0] would be 'car', [1] will be 'Toyota'
echo $caryouarelookingfor // output: "Toyota"
But, as also mentioned in the comments, the string looks like a corrupt piece of JSON, so perhaps you want to fix the construction of this string. :)
EDIT: typo in code, as said in first comment.
I get a string that looks like this
<br>
ACCEPT:YES
<br>
SMMD:tv240245ce
<br>
is contained in a variable $_session['result']
I am trying to parse through this string and get the following either in an array or as separate variables
ACCEPT:YES
tv240245ce
I first tried
to explode the string using as the delimiter, and that did not work
then I already tried
$yes = explode(":", strip_tags($_SESSION['result']));
echo print_r($yes);
which gives me an array like so
Array ( [0] => ACCEPT [1] => YESSEED [2] => tv240245ce ) 1
which gives me one of my answers.
Please what would be a great way of trying to achieve what I am trying to achieve?
is there a way to get rid of the first and last?
then use the remaining one as a delimiter to explode the string ?
or what's the best way to go about this ?
This will do it:
$data=preg_split('/\s?<br>\s?/', str_replace('SMMD:','',$data), NULL, PREG_SPLIT_NO_EMPTY);
See example here:
CodePad
You can also skip caring about the spurious <br> and treat the whole string as key:value format with a simple regex like:
preg_match_all('/^(\w+):(.*)/', $text, $result, PREG_SET_ORDER);
This requires that you really have line breaks in it though. Gives you a $result list which is easy to convert into an associative array afterwards:
[0] => Array
(
[0] => ACCEPT:YES
[1] => ACCEPT
[2] => YES
)
[1] => Array
(
[0] => SMMD:tv240245ce
[1] => SMMD
[2] => tv240245ce
)
First, do a str_replace to remove all instances of "SMMD:". Then, Explode on "< b r >\n". Sorry for weird spaced, it was encoding the line break.
Include the new line character and you should get the array you want:
$mystr = str_replace( 'SMMD:', '', $mystr );
$res_array = explode( "<br>\n", $mystr );
Right now i'm trying to get this:
Array
(
[0] => hello
[1] =>
[2] => goodbye
)
Where index 1 is the empty string.
$toBeSplit= 'hello,,goodbye';
$textSplitted = preg_split('/[,]+/', $toBeSplit, -1);
$textSplitted looks like this:
Array
(
[0] => hello
[1] => goodbye
)
I'm using PHP 5.3.2
[,]+ means one or more comma characters while as much as possible is matched. Use just /,/ and it works:
$textSplitted = preg_split('/,/', $toBeSplit, -1);
But you don’t even need regular expression:
$textSplitted = explode(',', $toBeSplit);
How about this:
$textSplitted = preg_split('/,/', $toBeSplit, -1);
Your split regex was grabbing all the commas, not just one.
Your pattern splits the text using a sequence of commas as separator (its syntax also isn't perfect, as you're using a character class for no reason), so two (or two hundred) commas count just as one.
Anyway, since your just using a literal character as separator, use explode():
$str = 'hello,,goodbye';
print_r(explode(',', $str));
output:
Array
(
[0] => hello
[1] =>
[2] => goodbye
)