Big string to nice array - php

I need to make big string into a nice array. String itself is list of tags and tag ids. There can be any amount of them. Here is example of the string: 29:funny,30:humor,2:lol - id:tag_name. Now, I have problem converting it to array - Array ( [29] => funny [30] => humor ). I can get to the part where tags are as so
Array (
[0] = Array (
[0] = 29
[1] = funny
)
[1] = Array (
[0] = 30
[1] = humor
)
)
I've look at array functions too but seems none of them could help me.
Can anyone help me out?

Here's some code to get you going:
$str = "29:funny,30:humor,2:lol";
$arr = array();
foreach (explode(',', $str) as $v) {
list($key, $val) = explode(':', $v);
$arr[$key] = $val;
}
print_r($arr);
/* will output:
Array
(
[29] => funny
[30] => humor
[2] => lol
)
*/
You could replace the foreach with an array_map for example, but I think it's simpler for you this way.
Here's an example of it working: http://codepad.org/4BpnCiEJ

You could use explode() to do this, though it would take two passes. The first to split the string into pairings (explode (',', $string)) and the second to split each paring
$arr = explode (',', $string);
foreach ($arr as &$pairing)
{
$pairing = explode (':', $pairing);
}

$string = '29:funny,30:humor,2:lol';
$arr1 = explode(',', $string);
$result = array();
foreach ($arr1 as $element1) {
$result[] = explode(':', $element1);
}
print_r($result);

You can use preg_match_all
preg_match_all('#([\d]+):([a-zA-Z0-9]+)#', $sString, $aMatches);
// Combine the keys with the values.
$aArray = array_combine($aMatches[1], $aMatches[2]);
echo "<pre>";
print_r($aArray);
echo "</pre>";
Outputs:
Array
(
[29] => funny
[30] => humor
[2] => lol
)

<?php
$test = '29:funny,30:humor,2:lol';
$tmp_array = explode(',', $test);
$tag_array = ARRAY();
foreach ($tmp_array AS $value) {
$pair = explode(':', $value);
$tag_array[$pair[0]] = $pair[1];
}
var_dump($tag_array);
?>

Related

PHP Array Inconsistency?

I have some code that pushes values into a PHP array via array_push(). However, when I do print_r() on the array, it skips a key, and the ending result looks like this:
Array (
[0] => appease
[1] => cunning
[2] => derisive
[3] => effeminate
[4] => grievance
[5] => inadvertently miscreants
[7] => ominous
[8] => resilient
[9] => resolute
[10] => restrain
[11] => superfluous
[12] => trudged
[13] => undiminished
)
As you can see, it skipped the 6th value, and moved onto the next one. For some reason though, if I call the foreach() method on the array, it stops after "grievance", or index 4. Does anyone know why it does this?
Edit: if I do echo $words[6], it prints the value of the 6th index correctly.
Edit 2: here's my code:
$return = file_get_contents($target_file);
$arr = explode('<U><B>', $return);
$a = 1;
$words = [];
foreach($arr as $pos) {
$important = substr($arr[$a], 0, 20);
$arr2 = explode("</B></U>",$important);
array_push($words,strtolower(trim($arr2[0])));
$a++;
}
Contents of the file are:
<U><B>appease</B></U><U><B>cunning</B></U><U><B>derisive</B></U><U><B>effeminate</B></U><U><B>grievance</B></U><U><B>inadvertently</B></U><U><B>miscreants</B></U><U><B>ominous</B></U><U><B>resilient</B></U><U><B>resolute</B></U><U><B>restrain</B></U><U><B>superfluous</B></U><U><B>trudged</B></U><U><B>undiminished</B></U>
*removed some irrelevant file content for easier readability
i wrote something simplier:
<?php
$return="<U><B>appease</B></U><U><B>cunning</B></U><U><B>derisive</B></U><U><B>effeminate</B></U><U><B>grievance</B></U><U><B>inadvertently</B></U><U><B>miscreants</B></U><U><B>ominous</B></U><U><B>resilient</B></U><U><B>resolute</B></U><U><B>restrain</B></U><U><B>superfluous</B></U><U><B>trudged</B></U><U><B>undiminished</B></U>";
$arr = explode('<U><B>', $return);
$words = [];
foreach($arr as $pos) {
if(!empty($pos)){
$words[]=strip_tags($pos);
}
}
echo '<pre>';
print_r($words);
demo: http://codepad.viper-7.com/XeUWui
$arr = "<U><B>appease</B></U><U><B>cunning</B></U><U><B>derisive</B></U><U><B>effeminate</B></U><U><B>grievance</B></U><U><B>inadvertently</B></U><U><B>miscreants</B></U><U><B>ominous</B></U><U><B>resilient</B></U><U><B>resolute</B></U><U><B>restrain</B></U><U><B>superfluous</B></U><U><B>trudged</B></U><U><B>undiminished</B></U>";
$arr = explode('<U><B>', $arr);
$a = 1;
foreach($arr as &$pos)
{
if(!empty($pos))
{
$pos = str_replace("</B></U>","",$pos);
}
}
print_r(array_filter($arr));
Might be overkill but there is always SimpleXml as well:
$arr = "<U><B>appease</B></U><U><B>cunning</B></U><U><B>derisive</B></U><U><B>effeminate</B></U><U><B>grievance</B></U><U><B>inadvertently</B></U><U><B>miscreants</B></U><U><B>ominous</B></U><U><B>resilient</B></U><U><B>resolute</B></U><U><B>restrain</B></U><U><B>superfluous</B></U><U><B>trudged</B></U><U><B>undiminished</B></U>";
$xml = new SimpleXmlElement('<root>' . $arr . '</root>');
$words = $xml->xpath('//B');
foreach ($words as $i =>$word) {
printf("%d.\t%s\n", $i+1, $word);
}
This is pretty simple with regex:
<?php
$words = "<U><B>appease</B></U><U><B>cunning</B></U><U><B>derisive</B></U><U><B>effeminate</B></U><U><B>grievance</B></U><U><B>inadvertently</B></U><U><B>miscreants</B></U><U><B>ominous</B></U><U><B>resilient</B></U><U><B>resolute</B></U><U><B>restrain</B></U><U><B>superfluous</B></U><U><B>trudged</B></U><U><B>undiminished</B></U>";
preg_match_all("#<U><B>(.*?)</B></U>#",$words,$matches);
print_r($matches[1]);
?>
Fiddle here

Create Multi dimension recursive regex with php pairs / array from preg_match_all

I have the following string which I need to be bale to extract the parameters from in order to process the next part of the code. I have manage to do this by doing multiple preg_match_all, but it is not very efficient and/or dynamic.
Example strings (the source might contain multiples):
<==OBJECTSTART==>type=>sqltable,objectid=>4000001,options=>1|5|2<==OBJECTEND==>
<==OBJECTSTART==>type=>sqltable,objectid=>4000002,options=>3|8|5<==OBJECTEND==>
What I have so far I have go to the following for a regex expression:
/<==OBJECTSTART==>((.?),)(.?)<==OBJECTEND==>/
This gives me the information before the first comma but I have tried the usual + and * to give me a repeat iteration but no luck.
ideally I am looking for an array of objects that looks like the following
[0]=>
[type]=sqltable
[objected]=4000001
[options]=1|5|2
[1]=>
[type]=sqltable
[objected]=4000002
[options]=3|8|5
thanks in advance!
This may not be the most elegant way of parsing this, but I think it gets the job done:
$str = <<<EOS
<==OBJECTSTART==>type=>sqltable,objectid=>4000001,options=>1|5|2<==OBJECTEND==>
<==OBJECTSTART==>type=>sqltable,objectid=>4000002,options=>3|8|5<==OBJECTEND==>
EOS;
foreach (explode(PHP_EOL, $str) as $line) {
$line = preg_replace('/<==OBJECTSTART==>(.*)<==OBJECTEND==>/', '\1', $line);
$pairs = explode(',', $line);
$data = array();
foreach ($pairs as $pair) {
list ($key, $value) = explode('=>', $pair);
$data[$key] = $value;
}
$result[] = $data;
}
print_r($result);
Output:
Array
(
[0] => Array
(
[type] => sqltable
[objectid] => 4000001
[options] => 1|5|2
)
[1] => Array
(
[type] => sqltable
[objectid] => 4000002
[options] => 3|8|5
)
)
First extract that is between <==OBJECTSTART==> and <==OBJECTEND==>
$str= substr($str, strlen("<==OBJECTSTART==>"), -1 * strlen("<==OBJECTEND==>"));
Then get all pairs attribute/value
preg_match_all("#([^\=]*)\=>([^\,<]*)#",str,values);
Finally, combines the keys and the values in a array
$result= array_combine( $values[1], $values[2] );

Joining array values into string

I have a PHP array with multiple objects. I'm trying to join values from a certain key into one string separated by commas. Output from var_dump:
Array
(
[0] => stdClass Object
(
[tag_id] => 111
[tag_name] => thing 1
[tag_link] => url_1
)
[1] => stdClass Object
(
[tag_id] => 663
[tag_name] => thing 2
[tag_link] => url_2
)
)
The string needs to be $string = 'thing 1,thing 2'. I tried using a foreach loop, but I'm completely stuck. Could anyone help out?
The above answer is a little light, maybe run it as a foreach loop instead.
$names = array();
foreach ($array as $k => $v) {
$names[] = $v->tag_name;
}
$string = implode(',', $names);
$output = '';
foreach($test as $t){
$output .= $t->tag_name . ',';
}
$output = substr($output, 0, -1);
echo $output;
Try as this
$string = $array[0]->tag_name.','.$array[1]->tag_name;
For other elements
$string = '';
foreach($array as $object) $string.=$object->tag_name.',';
$string = substr($string,0,-1);
Use something like this:
implode(',', array_map(function ($el) {
return $el->tag_name;
}, $array));

How can I send a php function an array like {28:1,29:0,30:1}?

I have set up an onclick to send a javascript function an array like this {28:1,29:0,30:1}.
I am wondering how I can send that to the php function so that when it is received, it is recognized as an array, rather than the form that it is in now.
If you need to transform your original string to array in php you can try
$str = '{28:1,29:0,30:1}';
$array = explode(',', trim($str, '{}'));
$result = array();
foreach ($array as $x)
{
list($key, $value) = explode(':', $x, 2);
$result[$key] = $value;
}
echo "<pre>"; print_r($result); will give you
Array
(
[28] => 1
[29] => 0
[30] => 1
)
Example

preg_match a "shortcode" to create an array with semantic array keys

How would I preg_match the following piece of "shortcode" so that video and align are array keys and their values are what is with in the quotes?
[video="123456" align="left"/]
Here is another approach using array_combine():
$str = '[video="123456" align="left"/][video="123457" align="right"/]';
preg_match_all('~\[video="(\d+?)" align="(.+?)"/\]~', $str, $matches);
$arr = array_combine($matches[1], $matches[2]);
print_r() output of $arr:
Array
(
[123456] => left
[123457] => right
)
$string='[video="123456" align="left"/]';
$string= preg_replace("/\/|\[|\]/","",$string);
$s = explode(" ",$string);
foreach ($s as $item){
list( $tag, $value) = explode("=",$item);
$array[$tag]=$value;
}
print_r($array);
Alternate solution with named parameters:
$str = '[video="123456" align="left"/][video="123457" align="right"/]';
$matches = array();
preg_match_all('/\[video="(?P<video>\d+?)"\salign="(?P<align>\w+?)"\/\]/', $str, $matches);
for ($i = 0; $i < count($matches[0]); ++ $i)
print "Video: ".$matches['video'][$i]." Align: ".$matches['align'][$i]."\n";
You could also reuse the previous array_combine solution given by Alix:
print_r(array_combine($matches['video'], $matches['align']));
I don't think there's any (simple) way to do it using a single regex, but this will work in a fairly general way, picking out the tags and parsing them:
$s = 'abc[video="123456" align="left"/]abc[audio="123456" volume="50%"/]abc';
preg_match_all('~\[([^\[\]]+)/\]~is', $s, $bracketed);
$bracketed = $bracketed[1];
$tags = array();
foreach ($bracketed as $values) {
preg_match_all('~(\w+)\s*=\s*"([^"]+)"~is', $values, $pairs);
$dict = array();
for ($i = 0; $i < count($pairs[0]); $i++) {
$dict[$pairs[1][$i]] = $pairs[2][$i];
}
array_push($tags, $dict);
}
//-----------------
echo '<pre>';
print_r($tags);
echo '</pre>';
Output:
Array
(
[0] => Array
(
[video] => 123456
[align] => left
)
[1] => Array
(
[audio] => 123456
[volume] => 50%
)
)

Categories