If I have a example string like this: "dataset1"=>"blank","gdataset"=>"f1,f2"
I'm trying to create an array of the key/value pairs.
Desired array result should look like this:
Array(
[0] => "dataset1"=>"blank"
[1] => "gdataset"=>"f1,f2"
)
I've tried http_build_query & explode w/o success, as the array key or value is getting mangled.
What should I use to get the desired array?
It's kind of hackish, but just replace "," with "","" to keep the quotes and then explode on ",":
$result = explode('","', str_replace('","', '"",""', $string));
But I'm positive that there is a much better way to do whatever you are doing in general. Maybe a new question outlining why you are doing this?
Related
Given the following code :
$str = 'CLAX';
echo $str[2]; //prints 'A'
then why should I use str_split( $str ) to convert string to a array of characters ?
I understand str_split( $str , 2 ) will return array of strings; each string being 2 characters long.
http://php.net/manual/en/function.str-split.php
This function is to split a string into an array with given string split length
By default string split length is set 1
If you want to split a string into given in given length, then you can use str_split. But in your case you are splitting string with default length 1 that is by you are getting confused.
<?php
$str = "CLAX";
echo $str[2]; //here you are referring to 2 index of string
$arr2 = str_split($str);
Array
(
[0] => C
[1] => L
[2] => A
[3] => X
)
echo $str[2]; //here you are referring to 2 index of an array
str_split reference
<?php
$str = "Hello Friend";
$arr2 = str_split($str, 3);
Array
(
[0] => Hel
[1] => lo
[2] => Fri
[3] => end
)
Using str_split() comes in pretty handy when you want to leverage array functions to perform a task on the components in a string.
str_split() works like explode() except it doesn't care what the characters are, just their position in the string -- there are specific use cases for this.
Use Case #1: Group Array Elements by Letter Range
Rather than manually declaring an array with 3 letters per element, like this:
$chunks=['ABC','DEF','GHI','JKL','MNO','PQR','STU','VWX','YZ']
The same array can be produced with:
$chunks=str_split(implode(range('A','Z')),3);
This purely for demonstration. Of course, declaring it manually would be more efficient. The potential benefit for other cases is code flexibility and ease of code modification.
Use Case #2: Convert string to array at different character occurence
Use str_split() when using a foreach loop to process each character.
$string="abbbaaaaaabbbb";
$array=str_split($string);
$last="";
foreach($array as $v){
if(!$last || strpos($last,$v)!==false){
$last.=$v;
}else{
$result[]=$last;
$last=$v;
}
}
$result[]=$last;
var_export($result);
If you try to supply the foreach loop with $string php will choke on it. str_split() is the right tool for this job.
Use Case #3: Find element of an array those contains only specific character set in PHP
Use str_split() to in association with other array functions to check values in a way that string functions are not well suited for.
[I'll refrain from transferring the full code block across.]
I want to extract the dimension from this given string.
$str = "enough for hitting practice. The dimension is 20'X10' *where";
I expect 20'X10' as the result.
I tried with the following code to get the number before and after the string 'X. But it is returning an empty array.
$regexForMinimumPattern ='/((?:\w+\W*){0,1})\'X\b((?:\W*\w+){0,1})/i';
preg_match_all ($regexForMinimumPattern, $str, $minimumPatternMatches);
print_r($minimumPatternMatches);
Can anyone please help me to fix this? Thanks in advance.
Just remove the \b from your pattern (and append a \' in the end if you want the trailing quote):
$regexForMinimumPattern ='/((?:\w+\W*){0,1})\'X((?:\W*\w+){0,1})\'/i';
NB: \b is the meta-character for word-boundaries, you don't need it here.
Assuming that the format of the string we want is 00'X00 :
$regexForMinimumPattern ='/[0-9]{1,2}\'X[0-9]{1,2}/i';
this gives you a result like
Array ( [0] => Array ( [0] => 20'X10 ) )
So: can a simple preg_replace()do that? Perhaps...
<?php
$str = "enough for hitting practice. The dimension is 20'X10' *where";
$dim = preg_replace("#(.*?)(\d*?)(\.\d*)?(')(X)(\d*?)(\.\d*)?(')(.+)#i","$2$3$4$5$6$7", $str);
var_dump($dim); //<== YIELDS::: string '20'X10' (length=6)
You may try it out Here.
Today i faced weird problem it is
$stringvar = '["image_link1","Image_link2"]';
Now i want to covert it into type array,
like
Array => [0] Image_link1, [1] Image_link2
I tried to juggling the type but it's giving me
Array => [0] '["image_link1","Image_link2"]'
Right now I am using
str_replace() to replace '[', ']' with blank. then explode.
Is there any best workaround for it?
The string is formatted in JSON notation.
PHP offers the convenient function json_decode() to decode that:
<?php
$stringvar = '["image_link1","Image_link2"]';
print_r(json_decode($stringvar));
The output of the above script is:
Array
(
[0] => image_link1
[1] => Image_link2
)
I didn't try your code but at first it looked weird for mee too.
I believe you can get rid off the apostrophes here $stringvar = '["image_link1","Image_link2"]';
so it gives you :
$stringvar = ["image_link1","Image_link2"];
This should work or you can also try :
$stringvar = array("image_link1","Image_link2");
Good luck ;)
I use PHP, I want to check if there is a name attribute and if thats is an array or an array with multiple levels,for example:
name="hello"
name="hello[]"
name="hello[1]"
name="hello[1][2]"
etc
I want to get hello and the array after it seperated and returned in an array i think:
array(hello,'')
array(hello,[])
array(hello,[1])
array(hello,[1][2])
something like that, so I can glue them back together or use seperatly later on
I think it must be done with regular expressions but how ?
Split on:
(?<!\])(?=\[)
This would split on the first [ character before which no ] character is encountered. eg.
$keywords = preg_split("/(?<!\])(?=\[)/", "hello[1][2]");
print_r($keywords);
Output
Array
(
[0] => hello
[1] => [1][2]
)
Background
I have an array which I create by splitting a string based on every occurrence of 0d0a using preg_split('/(?<=0d0a)(?!$)/').
For example:
$string = "78781110d0a78782220d0a";
will be split into:
Array ( [0] => 78781110d0a [1] => 78782220d0a )
A valid array element has to start with 7878 and end with 0d0a.
The Problem
But sometimes, there's an additional 0d0a in the string which splits into an extra and invalid array element, i.e., that doesn't begin with 7878.
Take this string for example:
$string = "78781110d0a2220d0a78783330d0a";
This is split into:
Array ( [0] => 78781110d0a [1] => 2220d0a [2] => 78783330d0a )
But it should actually be:
Array ( [0] => 78781110d0a2220d0a [1] => 78783330d0a)
My Solution
I've written the following (messy) code to get around this:
$data = Array('78781110d0a','2220d0a','78783330d0a');
$i = 0; //count for $data array;
$j = 0; //count for $dataFixed array;
$dataFixed = $data;
foreach($data as $packet) {
if (substr($packet,0,4) != "7878") { //if packet doesn't start with 7878, do some fixing
if ($i != 0) { //its the first packet, can't help it!
$j++;
if ((substr(strtolower($packet), -4, 4) == "0d0a")) { //if the packet doesn't end with 0d0a, its 'mostly' not valid, so discard it
$dataFixed[$i-$j] = $dataFixed[$i-$j] . $packet;
}
unset($dataFixed[$i-$j+1]);
$dataFixed = array_values($dataFixed);
}
}
$i++;
}
Description
I first copy the array to another array $dataFixed. In a foreach loop of the $data array, I check whether it starts with 7878. If it doesn't, I join it with the previous array in $data. I then unset the current array in $dataFixed and reset the array elements with array_values.
But I'm not very confident about this solution.. Is there a better, more efficient way?
UPDATE
What if the input string doesn't end in 0d0a like its supposed to? It will stick to the previous array element..
For e.g.: in the string 78781110d0a2220d0a78783330d0a0000, 0000 should be separated as another array element.
Use another positive lookahead (?=7878) to form:
preg_split('/(?<=0d0a)(?=7878)/',$string)
Note: I removed (?!$) because I wasn't sure what that was for, based on your example data.
For example, this code:
$string = "78781110d0a2220d0a78783330d0a";
$array = preg_split('/(?<=0d0a)(?=7878)(?!$)/',$string);
print_r($array);
Results in:
Array ( [0] => 78781110d0a2220d0a [1] => 78783330d0a )
UPDATE:
Based on your revised question of having possible random characters at the end of the input string, you can add three lines to make a complete program of:
$string = "78781110d0a2220d0a787830d0a330d0a0000";
$array = preg_split('/(?<=0d0a)(?=7878)/',$string);
$temp = preg_split('/(7878.*0d0a)/',$array[count($array)-1],null,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
$array[count($array)-1] = $temp[0];
if(count($temp)>1) { $array[] = $temp[1]; }
print_r($array);
We basically do the initial splitting, then split the last element of the resulting array by the expected data format, keeping the delimiter using PREG_SPLIT_DELIM_CAPTURE. The PREG_SPLIT_NO_EMPTY ensures we won't get an empty array element if the input string doesn't end in random characters.
UPDATE 2:
Based on your comment below where it seems you're implying there might be random characters between any of the desired matches, and you want these random characters preserved, you could do this:
$string = "0078781110d0a2220d0a2220d0a0000787830d0a330d0a000078781110d0a2220d0a0000787830d0a330d0a0000";
$split1 = preg_split('/(7878.*?0d0a)/',$string,null,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
$result = array();
foreach($split1 as $e){
$split2 = preg_split('/(.*0d0a)/',$e,null,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
foreach($split2 as $el){
// test if $el doesn't start with 7878 and ends with 0d0a
if(strpos($el,'7878') !== 0 && substr($el,-4) == '0d0a'){
//if(preg_match('/^(?!7878).*0d0a$/',$el) === 1){
$result[ count($result)-1 ] = $result[ count($result)-1 ] . $el;
} else {
$result[] = $el;
}
}
}
print_r($result);
The strategy employed here is different than above. First we split the input string based on the delimiter that matches your desired data, using the nongreedy regex .*?. At this point we have some strings that contain the ending of a desired value and some garbage at the end, so we split again based on the last occurrence of "0d0a" with the greedy regex .*0d0a. We then append any of those resulting values that don't start with "7878" but end with "0d0a" to the previous value, as this should repair the first and second halves that got split because it contained an extra "0d0a".
I provided two methods for the innermost if statement, one using regular expressions. The regex one is marginally slower in my testing, so I've left that one commented out.
I might still not have your full requirements, so you'll have to let me know if it works and perhaps provided your full dataset.
I think you are using a delimiter "0d0a" which also happens to be part of a content! Its not possible to avoid getting junk data as long as delimiter can also be part of content. Somehow delimiter must be unique.
Possible solutions.
Change the delimited to something else that doesn't occur as part of your data ( 000000, #!.;)
If you are definite about length of text that easy arrange item may have, use it. As per examples its not possible.
Solutions given in answers considering only sample data you have shared. If you are confidant about what will be the content of string, then these solutions given by others are pretty good to use. Otherwise these solutions wont assure you guarantee!
Best solution: Fix right delimiter then use regex or explode whatever you prefer.
Why don't you use preg_match_all instead? You can avoid all of the non-capturing groups (the look aheads, look behinds) in order to split the string (which without the non-capturing groups removes the matches), and just find the matches you're looking for:
Updated
<?php
$string = "00787817878110d0a22278780d0a78783330d0a00";
preg_match_all('/7878.*?0d0a(?=7878|[^(7878)]*?$)/', $string, $arr);
print_r($arr);
?>
Gives an array $arr[0] => ( [0] => 787817878110d0a22278780d0a, [1] => 78783330d0a ). Strips leading and trailing garbage characters (whatever doesn't start with 7878 or end with 7878 or 0d0a.
So $arr[0] would be the array of values that you are looking for.
See example on ideone
Works with multiple 7878 values and multiple 0d0a values (even though that's ridiculous).
Update
If splitting is more your style, why not avoid regular expressions altogether?
<?php
$string = "787817878110d0a22278780d0a78783330d0a";
$arr = explode('0d0a7878', $string);
$string = implode('0d0a,7878', $arr);
$arr = explode(',', $string);
print_r($arr);
?>
Here we split the string by the delimiter 0d0a7878, which is what #CharlieGorichanaz's solution is doing, and props to him for the quick, accurate solution. We then add a comma, because who doesn't love comma separated values? And we explode again on the commas for an array of desired values. Performance-wise, this ought to be faster than using regular expressions. See example.