PHP convert comma separated string with square brackets into array - php

My string looks like:
[10,20,30]
I want to convert it to an array.
I've tried:
$myArray=explode(",",$myString);
print_r($myArray);
But this is returning:
Array ( [0] => [10 [1] => 20 [2] => 30] )
I need to get rid of the opening/closing brackets.
Can someone help?

An array of numbers in that particular format is valid JSON, so you can use PHP’s built-in function:
$myArray = json_decode($myString);

I think you can remove the square brackets first with str_replace function. Then you can simply do the rest. This will work I think.
$inputString = "[10,20,30]";
$processString = str_replace(array('[',']') ,'' , $inputString);
$outputArray = explode(',' , $processString);
var_dump($outputArray);
//output:
//array(3) { [0]=> string(2) "10" [1]=> string(2) "20" [2]=> string(2) "30" }

Related

php how to split an array string into two by condition

i have a simple array of prices, which is formed as a result of data entry by users
array(4) {
[0] => string(4) "18"
[1] => string(4) "20"
[2] => string(4) "10"
[3] => string(4) "17"
}
The minimum and maximum values ​​are displayed in the frontend like 10-20$
But, in one field, the user can enter a range of values, like this:
array(3) {
[0]=> string(9) "18-28"
[2]=> string(9) "10-15"
[3]=> string(9) "16-22"
}
And then the range is displayed as 10-15-18-28$
How to break the lines of array into two, if the line has a "-" or "/"?
Thanks for help:)
You might use explode and use the dash or forward slash as the delimiter. If you want to display the highest and the lowest, you could sort them and use for example rsort.
$a = [
"18-28",
"18-29",
"10-15",
"16-22"
];
rsort($a);
print_r($a);
Result
Array
(
[0] => 18-29
[1] => 18-28
[2] => 16-22
[3] => 10-15
)
Then you can get the first item from the array as the highest and the last item as the lowest range.
echo reset($a).'$'; // 18-29$
echo end($a).'$'; // 10-15$
Php demo
You could use a combination of explode and implode:
$a = [
'18-28',
'10-15',
'16-22'
];
$b = explode('-',implode('-',$a));
echo min($b).'-'.max($b).'$'; // result: 10-28$
If the input may also contain spaces or other dummy characters, or people erratically enter price ranges as "18/28" or "18~28" instead of "10-28" or whatever, a more fool-proof way would be:
$a = [
// crappy formatted example input
'18 - 28 ',
'10/15$',
' 16~22'
];
$b = explode(' ',trim(preg_replace('#[^0-9.]+#si',' ',implode(' ',$a))));
echo min($b).'-'.max($b).'$'; // result: 10-28$
What this does is:
implode all elements of $a into a single string, glued together with spaces
replace all non-numeric parts of the string (anything that isn't a digit or dot) into a single space
trim the string to remove any redundant spaces at the beginning and end (to avoid empty elements)
explode the string using a space as separator, to create a new array containing all individual numbers
take the min and max of the resulting array
If you don't want to support floating point numbers (like 9.95) then remove the dot in the regular expression, i.e. that becomes '#[^0-9]+#si'.

PHP: How to explode() string of Chinese Characters

Hello I have this string
$chineseString = "号码:91"
What I want to do is to explode() it and get a result like this:
array:2[
[0] => "号码",
[1] => "91"
]
The reason explode() didn't work for you is that your chineseString variable contains what is called in unicode a FULLWIDTH COLON (U+FF1A) and you are trying to split by a different character, a COLON (U+003A). So, if you use the correct character it will work.
$chineseString = "号码:91";
print_r(explode(":", $chineseString ));
Outputs: Array([0] => 号码, [1] => 91)
Take a look at this http://codepad.org/yYO3nljF
<?php
$chineseString = "号码:91";
$d = explode(":",$chineseString );
var_dump($d);
?>
output
array(2) {
[0]=>
string(6) "号码"
[1]=>
string(2) "91"
}
This seems to work for me:
$chineseString = "号码:91";
print_r(preg_split('/:/', $chineseString));
Results in: Array ( [0] => 号码 [1] => 91 )

Recognize multiple strings starting with #

I want my php to recognize multiple strings in a string starting with the # symbol. Those shall then be converted into variables
//whole string
$string = "hello my name is #mo and their names are #tim and #tia."
//while loop now?
#mo #tim #tia shall then be converted to variables like:
$user1 = "mo";
$user2 = "tim";
$user3 = "tia";
Is there a php command you can use to collect them all in an array?
Regular expressions are a very flexible tool for pattern recognition:
<?php
$subject = "hello my name is #mo and their names are #tim and #tia.";
$pattern = '/#(\w+)/';
preg_match_all($pattern, $subject, $tokens);
var_dump($tokens);
The output is:
array(2) {
[0] =>
array(3) {
[0] =>
string(3) "#mo"
[1] =>
string(4) "#tim"
[2] =>
string(4) "#tia"
}
[1] =>
array(3) {
[0] =>
string(2) "mo"
[1] =>
string(3) "tim"
[2] =>
string(3) "tia"
}
}
So $token[1] is the array you are interested in.
Perhaps, you use a regex to match all those string starting with "#" and put it in an array?
preg_match_all("|\#(.*)[ .,]|U",
"hello my name is #mo and their names are #tim and #tia.",
$out, PREG_PATTERN_ORDER);
out now has the matched strings..
PS: Am not a PHP developer. Just tried out something using online
compiler.!

PHP Parse Comma Separated String with double quotes

I have a url parameter named data that contains a comma separated string with some enclosed in double quotes like this:
localhost/index.php?data=val1,val2,val3,"val4","val5",val6
I am trying to parse the string and put it into an array. Using str_getcsv($_GET['data'],',','"'); gives me the output like this:
Array
(
[0] => val1
[1] => val2
[2] => val3
[3] =>
)
I would like the array to look like this:
Array
(
[0] => val1
[1] => val2
[2] => val3
[3] => val4
[4] => val5
[5] => val6
)
Thanks in advance!
I would say urlencode the double quotes when generating that url. Because link will result in the url you go to only being localhost/index.php?data=val1,val2,val3,
So like:
echo 'link';
Have you tried using explode? It'll separate a string into an array using whatever separator you specify.
Using your example,
$_GET['data'] = 'val1,val2,val3,"val4","val5",val6';
$testarr = explode(",", $_GET['data']);
var_dump($testarr);
Outputs:
array(6) {
[0]=>
string(4) "val1"
[1]=>
string(4) "val2"
[2]=>
string(4) "val3"
[3]=>
string(6) ""val4""
[4]=>
string(6) ""val5""
[5]=>
string(4) "val6"
}
Looking at your question again, it seems you might want to remove the " from $_GET['data'] entirely?. If so, do this:
$testarr = explode(",", str_replace('"','',$_GET['data']));

How does one split a string on two delimeters into an associative array

The answer on this question, pointed me in a possible direction, but it processes the string once, then loops through the result. Is there a way to do it in one process?
My string is like this, but much longer:
954_adhesives
7_air fresheners
25_albums
236_stuffed_animial
819_antenna toppers
69_appliances
47_aprons
28_armbands
I'd like to split it on linebreaks, then on underscore so that the number before the underscore is the key and the phrase after the underscore is the value.
Just use a regular expression and array_combine:
preg_match_all('/^([0-9]+)_(.*)$/m', $input, $matches);
$result = array_combine($matches[1], array_map('trim', $matches[2]));
Sample output:
array(8) {
[954]=>
string(9) "adhesives"
[7]=>
string(14) "air fresheners"
[25]=>
string(6) "albums"
[236]=>
string(15) "stuffed_animial"
[819]=>
string(15) "antenna toppers"
[69]=>
string(10) "appliances"
[47]=>
string(6) "aprons"
[28]=>
string(8) "armbands"
}
Use ksort or arsort if you need the result sorted as well, by keys or values respectively.
You can do it in one line:
$result = preg_split('_|\n',$string);
Here is a handy-dandy tester: http://www.fullonrobotchubby.co.uk/random/preg_tester/preg_tester.php
EDIT:
For posterity, here's my solution. However, #Niels Keurentjes answer is more appropriate, as it matches a number at the beginning.
If you wanted to do this with regular expressions, you could do something like:
preg_match_all("/^(.*?)_(.*)$/m", $content, $matches);
Should do the trick.
If you want the result to be a nested array like this;
Array
(
[0] => Array
(
[0] => 954
[1] => adhesives
)
[1] => Array
(
[0] => 7
[1] => air fresheners
)
[2] => Array
(
[0] => 25
[1] => albums
)
)
then you could use an array_map eg;
$str =
"954_adhesives
7_air fresheners
25_albums";
$arr = array_map(
function($s) {return explode('_', $s);},
explode("\n", $str)
);
print_r($arr);
I've just used the first three lines of your string for brevity but the same function works ok on the whole string.

Categories