I have a string which contains quite a bit of data. I want to split the data into a 2D array. The data in the string is split by a ~ (tilde) for the columns and a : (colon) for the different rows.
An example string could be: "London~10~20~cold:New York~23~53~hot:Madrid~43~12~dry".
Thanks.
$string = "London~10~20~cold:New York~23~53~hot:Madrid~43~12~dry";
$array = explode(':', $string);
foreach($array as &$value) $value = explode('~', $value);
Functional way (PHP 5.3.x needed):
$string = "London~10~20~cold:New York~23~53~hot:Madrid~43~12~dry";
$map = array_map(function($el) {
return explode('~', $el);
}, explode(':', $string));
Another alternative would be:
preg_match_all('/(.*?)~(.*?)~(.*?)~(.*?)(?:$|:)/', $string, $array,
PREG_SET_ORDER);
It's more cumbersome in that you have to predefine the column format. It also returns the complete match in each rows [0]. Otherwise (due to PREG_SET_ORDER) it's in your desired 2d format.
Just posting it here to please and annoy the microoptimizers at the same time. Despite the common Stackoverflow meme, the regex is three times faster than the explode loop.
You can split data in php with explode().
So first you have to split the string, than you have to split your entries again with explode().
$data = explode(':', $string);
$array = array();
foreach($data as $d) {
$d = explode('~', $d);
$array[] = $d; //e.g. $array[0][0] --> London
//$array[$d[0]] = array('temperature' => $d[1], 'dont-know' => $d[2], 'climate' => $d[3]); //e.g. $arra['London'] => array(...)
}
A "functional" style
$array = array_map(function($value) {
return explode('~', $value);
}, explode(':',$string););
Related
I have a string of this type:
string(11) "2=OK, 3=OK"
from a text file. But I would like to convert it into an array of keys this type :
array (
[2] => Ok
[3] => Ok
)
I was wondering how we could do that in PHP.
Note:- I normally use explode() and str_split() for the conversions string into array but in this case I don't know how to do it.
use explode(), foreach() along with trim()
<?php
$string = "2=OK, 3=OK" ;
$array = explode(',',$string);
$finalArray = array();
foreach($array as $arr){
$explodedString = explode('=',trim($arr));
$finalArray[$explodedString[0]] = $explodedString[1];
}
print_r($finalArray);
https://3v4l.org/ZsNY8
Explode the string by ',' symbol. You will get an array like ['2=OK', ' 3=OK']
Using foreach trim and explode each element by '=' symbol
You can use default file reading code and traverse it to achieve what you want,
$temp = [];
if ($fh = fopen('demo.txt', 'r')) {
while (!feof($fh)) {
$temp[] = fgets($fh);
}
fclose($fh);
}
array_walk($temp, function($item) use(&$r){ // & to change in address
$r = array_map('trim',explode(',', $item)); // `,` explode
array_walk($r, function(&$item1){
$item1 = explode("=",$item1); // `=` explode
});
});
$r = array_column($r,1,0);
print_r($r);
array_walk — Apply a user supplied function to every member of an array
array_map — Applies the callback to the elements of the given arrays
explode — Split a string by a string
Demo.
You can use preg_match_all along with array_combine, str_word_count
$string = "2=OK, 3=OK" ;
preg_match_all('!\d+!', $string, $matches);
$res = array_combine($matches[0], str_word_count($string, 1));
Output
echo '<pre>';
print_r($res);
Array
(
[2] => OK
[3] => OK
)
LIVE DEMO
i know that its easy to extract string between two slashes using explode() function in php, What if the string is like
localhost/used_cars/search/mk_honda/md_city/mk_toyota
i want to extract string after mk_ and till the slashes like:** honda,toyota **
any help would be highly appreciated.
I am doing like this
echo strpos(uri_string(),'mk') !== false ? $arr = explode("/", $string, 2);$first = $arr[0]; : '';
but not working because if user enter mk_honda in any position then explode() is failed to handle that.
Use regex:
http://ideone.com/DNHXsf
<?php
$input = 'localhost/used_cars/search/mk_honda/md_city/mk_toyota';
preg_match_all('#/mk_([^/]*)#', $input, $matches);
print_r($matches[1]);
?>
Output:
Array
(
[0] => honda
[1] => toyota
)
Explode your string by /, then check every element of array with strpos:
$string = 'localhost/used_cars/search/mk_honda/md_city/mk_toyota';
$parts = explode('/', $string);
$r = [];
foreach ($parts as $p) {
// use `===` as you need `mk_` in position 0
if (strpos($p, 'mk_') === 0) {
// 3 is a length of `mk_`
$r[] = substr($p, 3);
}
}
echo'<pre>',print_r($r),'</pre>';
Just try this
$str='localhost/used_cars/search/mk_honda/md_city/mk_toyota';
$str=explode('/',$str);
$final=[];
foreach ($str as $words){
(!empty(explode('_',$words)))?(isset(explode('_',$words)[1]))?$final[]=explode('_',$words)[1]:false:false;
}
$final=implode(',',$final);
echo $final;
It give output as
cars,honda,city,toyota
I have string of comma separated values.
1,2,3,4,4,4,4,4,4,4,4,01633,4,4
I need to remove the duplicates, so I though of using
array_unique($str);
However, it returns no results. So I decided to output it to see what I have:
print_r($str);
// returns: 1,2,3,4,4,4,4,4,4,4,4,01633,4,4
I'm a little lost. I checked if it is an array and I got true. Here's how that string is created:
$str = '1,2,3';
foreach ($a as $b) {
$str.= ','.$b;
}
What am I missing here?
$str = explode(',', $str); // create array
$newArray = array_unique($str); // then process
actually, though... just do your array_unique() on $a before the string is created.
$a = array_unique($a);
then...
foreach ($a as $b) { // and so on
Convert to an array, remove the repeat values, convert to string
$str = 'whatever';
$arr = explode( ',', $str );
$newArr = array_unique( $arr );
$newStr = implode( ',', $newArr );
Explode on comma, make unique, glue pieces back together:
$str = implode(',', array_unique(explode(',', $str)));
I have a string like this:
key=value, key2=value2
and I would like to parse it into something like this:
array(
"key" => "value",
"key2" => "value2"
)
I could do something like
$parts = explode(",", $string)
$parts = array_map("trim", $parts);
foreach($parts as $currentPart)
{
list($key, $value) = explode("=", $currentPart);
$keyValues[$key] = $value;
}
But this seems ridiciulous. There must be some way to do this smarter with PHP right?
If you don't mind using regex ...
$str = "key=value, key2=value2";
preg_match_all("/([^,= ]+)=([^,= ]+)/", $str, $r);
$result = array_combine($r[1], $r[2]);
var_dump($result);
<?php parse_str(str_replace(", ", "&", "key=value, key2=value2"), $array); ?>
if you change your string to use & instead of , as the delimiter, you can use parse_str()
If you can change the format of the string to conform to a URL query string (using & instead of ,, among other things, you can use parse_str. Be sure to use the two parameter option.
Here's a single command solution using array_reduce formatted in multple lines for readability:
<?php
$str = "key=value, key2=value2";
$result = array_reduce(
explode(',', $str),
function ($carry, $kvp) {
list($key, $value)=explode('=', $kvp);
$carry[trim($key)]=trim($value);
return $carry;
}, []);
I'd like to explode a multi-line-string like this
color:red
material:metal
to an array like this
$array['color']=red
$array['material']=metal
any idea?
Use explode(), you can use a regexp for it, but it's simple enough without the overhead.
$data = array();
foreach (explode("\n", $dataString) as $cLine) {
list ($cKey, $cValue) = explode(':', $cLine, 2);
$data[$cKey] = $cValue;
}
As mentioned in comments, if data is coming from a Windows/DOS environment it may well have CRLF newlines, adding the following line before the foreach() would resolve that.
$dataString = str_replace("\r", "", $dataString); // remove possible \r characters
The alternative with regexp can be quite pleasant using preg_match_all() and array_combine():
$matches = array();
preg_match_all('/^(.+?):(.+)$/m', $dataString, $matches);
$data = array_combine($matches[1], $matches[2]);
Try this
$value = '1|a,2|b,3|c,4|d';
$temp = explode (',',$value);
foreach ($temp as $pair)
{
list ($k,$v) = explode ('|',$pair);
$pairs[$k] = $v;
}
print_r($pairs);
explode first on line break. Prolly \n
Then explode each of the resulting array's items on : and set a new array to that key/value.