I have 3 strings in PHP which contains a list of test input for a function with two parameters.
I want to parse the strings and get the individual parameter values.
example:
"a,b" => "a", "b"
"/"string_param1/", /"string_param2/"" => "string_param1", "string_param2"
"[list,1], [list,2]" => "[list,1]", "[list,2]"
For strings 1 and 3 you can use the explode function to split the string at the comma like so:
$a = 'a,b';
$a_params = explode(',', $a);
But for the second string you can run str_replace to get rid of unwanted quotes or backslashes so you can use explode.
str_replace() documentation
explode() documentation
You cannot simply use explode() because you have other factor to accommodate.
preg_split() is the function to call when you want to perform a variable explosion.
(*SKIP)(*FAIL) is a very handy technique for this case because it consumes the "protected" substrings and then disqualifies them as possible splitting points.
The , ? (comma - space - questionmark) means that you want to explode on every comma that is optionally trailed by a space.
Code: (Demo)
$test_strings = ['a,b', '/"string_param1/", /"string_param2/"', '[list,1], [list,2]'];
foreach ($test_strings as $string) {
$result[] = preg_split('~(?:\".*?\"|\[[^[]*])(*SKIP)(*FAIL)|, ?~', $string, -1, PREG_SPLIT_NO_EMPTY);
}
var_export($result);
Output:
array (
0 =>
array (
0 => 'a',
1 => 'b',
),
1 =>
array (
0 => '/"string_param1/"',
1 => '/"string_param2/"',
),
2 =>
array (
0 => '[list,1]',
1 => '[list,2]',
),
)
Related
Currently I am trying to split the � the special character which represents %A0 at the URL. However when I use another URL, it doesn't recognize %A0 therefore I need to use %20 which is the standard space.
My question is. Is there a way to explode() special character �? Whenever I try to explode, it always return a single index array with length 1 array.
//Tried str_replace() to replace %A0 to empty string. Didn't work
$a = str_replace("%A0"," ", $_GET['view']);
// Tried to explode() but still returning single element
$b = explode("�", $a);
// Returning Array[0] => "Hello World" insteand of
// Array[2] => [0] => "Hello", [1] => "World"
echo $b[0];
Take a look at mb_split:
array mb_split ( string $pattern , string $string [, int $limit = -1 ] )
Split a multibyte string using regular expression pattern and returns
the result as an array.
Like this:
$string = "a�b�k�e";
$chunks = mb_split("�", $string);
print_r($chunks);
Outputs:
Array
(
[0] => a
[1] => b
[2] => k
[3] => e
)
How do I split a string by , but skip the one that's inside an array
String - "'==', ['abc', 'xyz'], 1"
When I do explode(',', $expression) it's giving me 4 item in array
array:4 [
0 => "'=='"
1 => "['abc'"
2 => "'xyz']"
3 => 1
]
But I want my output to be -
array:3 [
0 => "'=='"
1 => "['abc', 'xyz']"
2 => 1
]
yeah, regex - select all commas, ignore in square brakets
/[,]+(?![^\[]*\])/g
https://regexr.com/3qudi
For your example data you might use preg_split and use a regex to match a comma or match the part with the square brackets and then skip that using (*SKIP)(*FAIL).
,|\[[^]]+\](*SKIP)(*FAIL)
$pattern = '/,|\[[^]]+\](*SKIP)(*FAIL)/';
$string = "'==', ['abc', 'xyz'], 1";
$result = preg_split($pattern, $string);
print_r($result);
That would give you:
Array
(
[0] => '=='
[1] => ['abc', 'xyz']
[2] => 1
)
Demo
For your example, if you don't want to use regex and want to stick with the explode() function you are already using, you could simply replace all instances of ', ' with ',', then break the string in parts by , (followed by a space) instead of just the comma.
This makes it so things inside the brackets don't have the explode delimiter, thus making them not break apart into the array.
This has an additional problem, if you had a string like '==', 'test-taco', this solution would not work. This problem, along with many other problems probably, can be solved by removing the single quotes from the separate strings, as ==, test-taco would still work.
This solution should work if your strings inside brackets are valid PHP arrays/JSON string
$str = "'==', ['abc', 'xyz'], 1";
$str = str_replace("', '", "','", $str);
$str = explode(", ", $str);
Though I recommend regex as it may solve some underlying issues that I don't see.
Output is:
Array
(
[0] => '=='
[1] => ['abc','xyz']
[2] => 1
)
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'm trying to figure out how to split a string that looks like this :
a20r51fx500fy3000
into an associative array that will look like this :
array(
'a' => 20,
'r' => 51,
'fx' => 500,
'fy' => 3000,
);
I don't think I can use preg_split as this will drop the character I'm splitting on (I tried /[a-zA-Z]/ but obviously that didn't do what I wanted it to). I'd prefer if I could do it using some kind of built-in function, but I don't really mind looping if that's required.
Any help would be much appreciated!
Multiple Matches and PREG_SET_ORDER
Do this:
$yourstring = "a20r51fx500fy3000";
$regex = '~([a-z]+)(\d+)~';
preg_match_all($regex,$yourstring,$matches,PREG_SET_ORDER);
$yourarray=array();
foreach($matches as $m) {
$yourarray[$m[1]] = $m[2];
}
print_r($yourarray);
Output:
Array ( [a] => 20 [r] => 51 [fx] => 500 [fy] => 3000 )
If your string can contain upper-case letters, make the regex case-insensitive by adding the i flag after the closing delimiter: $regex = '~([a-z]+)(\d+)~i';
Explanation
([a-z]+) captures letters to Group 1
(\d+) captures digits to Group 1
$yourarray[$m[1]] = $m[2]; creates in index for the letters, and assigns the digits
I need to split my GET string into some array. The string looks like this:
ident[0]=<IDENT_0>&value[0]=<VALUE_0>&version[0]=<VERSION_0>&....&ident[N]=<IDENT_N>&value[N]=<VALUE_N>&version[N]=<VERSION_N>
So, I need to split this string by every third ampersand character, like this:
ident[0]=<IDENT_0>&value[0]=<VALUE_0>&version[0]=<VERSION_0>
ident[1]=<IDENT_1>&value[1]=<VALUE_1>&version[1]=<VERSION_1> and so on...
How can I do it? What regular expression should I use? Or is here some better way to do it?
There is a better way (assuming this is data being sent to your PHP page, not some other thing you're dealing with).
PHP provides a "magic" array called $_GET which already has the values parsed out for you.
For example:
one=1&two=2&three=3
Would result in this array:
Array ( [one] => 1 [two] => 2 [three] => 3 )
So you could access the variables like so:
$oneValue = $_GET['one']; // answer is 1
$twoValue = $_GET['two']; // and so on
If you provide array indexes, which your example does, it'll sort those out for you as well. So, to use your example above $_GET would look like:
Array
(
[ident] => Array
(
[0] => <IDENT_0>
[N] => <IDENT_N>
)
[value] => Array
(
[0] => <VALUE_0>
[N] => <VALUE_N>
)
[version] => Array
(
[0] => <VERSION_0>
[N] => <VERSION_N>
)
)
I'd assume your N keys will actually be numbers, so you'll be able to look them up like so:
$_GET['ident'][0] // => <IDENT_0>
$_GET['value'][0] // => <VALUE_0>
$_GET['version'][0] // => <VERSION_0>
You could loop across them all or whatever, and you will never have to worry about splitting them all out yourself.
Hope it helps you.
You can use preg_split with this pattern: &(?=ident)
$result = preg_split('~&(?=ident)~', $yourstring);
regex detail: &(?=ident) means & followed by ident
(?=..) is a lookahead assertion that performs only a check but match nothing.
Or using preg_match_all:
preg_match_all('~(?<=^|&)[^&]+&[^&]+&[^&]+(?=&|$)~', $yourstring, &matches);
$result = $matches[0];
pattern detail: (?<=..) is a lookbehind assertion
(?<=^|&) means preceded by the begining of the string ^ or an ampersand.
[^&]+ means all characters except the ampersand one or more times.
(?=&|$) means followed by an ampersand or the end of the string $.
Or you can use explode, and then a for loop:
$items = explode('&', $yourstring);
for ( $i=0; $i<sizeof($items); $i += 3 ) {
$result[] = implode('&', array_slice($items, $i, 3));
}