How can i split data from string in php? - php

I have a string in PHP like the following
$data = "ID=53KEY=23";
and i want to assign value from this string to following variables
$id = 53;
$key = 23;
How can i do this in php, please help?

This function will work for more generic key/value inputs, not just ID/KEY
$input = "ID=53KEY=23";
$res = preg_split("/([[:upper:]]+)=([[:digit:]]+)/", $input, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
for ($i = 0 ; $i < count($res) ; $i += 2)
{
$res[$i] = strtolower($res[$i]);
$$res[$i] = $res[$i+1];
}
//$id = 53
//$key = 23

For a more generic solution:
$data = "ID=53KEY=23AGE=318";
$array = array();
if(preg_match_all("/([A-Z]+)=(\d+)/", $data, $matches)) {
$array = array_change_key_case(array_combine($matches[1], $matches[2]));
}
echo "ID: " . $array['id'] . ", KEY: " . $array['key'] . ", AGE: " . $array['age'];

Try this:
$data = "ID=53KEY=23";
preg_match("/id=(?<id>\d+)&?key=(?<key>\d+)/i",$data,$array);
$id = $array["id"]; // 53
$key = $array["key"]; //23
print("id = $id, key = $key\n");

Related

how to explode following string

How do i explode a following string
$str = "ProductId=123, Name=Ancient Roots, Modern Pursuits, Country=India, City=Bangalore, Price=3368"
Such that output array will contain
[
"ProductId" => "123",
"Name" => "Ancient Roots, Modern Pursuits",
"Country" => "India",
"City" => "Bangalore",
"Price" => "3368"
]
I tried to explode by "comma", then each element again explode by "equal to" as.
$arr = explode(",", $str);
and again
$prodarr = explode("=", $arr[0]);
$product["ProductId"] = $prodarr[1]
But facing problem when another comma is exist in value like in name "Ancient Roots, Modern Pursuits"
Your structure is very weak for breaking. But you can still try to parse it.
First explode on =. You will have next key and current value.
Then loop these and explode on , and select last element for next key and all previous parts as value (sample):
<?php
$str = "ProductId=123, Name=Ancient Roots, Modern Pursuits, Country=India, City=Bangalore, Price=3368";
$chunks = explode('=', $str);
$keys = [];
$values = [];
foreach ($chunks as $i => $chunk) {
$parts = explode(',', $chunk);
if ($i != count($chunks) - 1) {
$keys[] = trim(array_pop($parts));
}
if ($i != 0) {
$values[] = implode(',', $parts);
}
}
var_dump(array_combine($keys, $values));
I played a little bit around. I used preg_match_all() to extract the Patterns which contain characters that are no , and no = followed by a = followed by characters that are no = followed by a , or end of line. here is the result:
$result = array();
preg_match_all('/([^=,]+=[^=]+)(,|$)/', $string, $matches);
foreach($matches[1] as $data){
$data = explode('=', $data);
$result[trim($data[0])] = trim($data[1]);
}
$result = json_encode($result);
The result is:
{"ProductId":"123","Name":"Ancient Roots, Modern Pursuits","Country":"India","City":"Bangalore"}
Try something like this
<?php
$str = "ProductId=123, Name=Ancient Roots, Modern Pursuits, Country=India, City=Bangalore, Price=3368";
$str_arr = explode(",", $str);
$json_array = array();
for ($i = 0; $i < sizeof($str_arr); $i++)
{
if (isset($str_arr[$i + 1]))
{
if (strpos($str_arr[$i + 1], '=') !== false)
{
$prod = explode("=", $str_arr[$i]);
$json_array["" . $prod[0] . ""] = "" . $prod[1] . "";
}
else
{
$textAppend = "," . $str_arr[$i + 1];
$prod = explode("=", $str_arr[$i]);
$json_array["" . $prod[0] . ""] = "" . $prod[1] . "" . $textAppend . "";
$i++;
}
}
else
{
$prod = explode("=", $str_arr[$i]);
$json_array["" . $prod[0] . ""] = "" . $prod[1] . "";
}
}
var_dump($json_array);
?>

Php serialize() values to comma separated string values

Hello i am trying to convert PHP serialize strings into comma separated values for a absolutely absurd client requirement :P Here's the code!!!
$o = [1,2,3,4,5,6];
$l = serialize($o);
$o = [$l,$l,$l];
echo '<pre>';
$m = array();
print_r($o);
echo '-----------------------------------' . '<br>';
for($i=0;$i<count($o);$i++)
{
$d = unserialize($o[$i]);
$y = '';
for($q=0;$q<count($d);$q++)
{
$r = $d[$q] ;
$y = $y.$r.',';
//echo $r . ',';
}
//echo $y;
array_push($m,$y);
//echo '<br>';
}
print_r($m);
If I were your, I would use implode to serialize strings into comma separated values.
I've modified you code to this:
$o = array(1,2,3,4,5,6);
$l = serialize($o);
$o = array($l,$l,$l);
echo '<pre>';
$m = array();
print_r($o);
echo '-----------------------------------' . '<br>';
for($i=0;$i<count($o);$i++)
{
$d = unserialize($o[$i]);
// using implode for briefer
$m[] = implode(',', $d);
}
print_r($m);

Double the font-size in string with HTML/CSS content

I've got a string like this:
$foo = 'height:200px;color:#CCC;font-size:12px';
Can I somehow double the font-size amount in the string?
Try with:
$foo = 'height:200px;color:#CCC;font-size:12px';
$key = 'font-size:';
preg_match('/' . $key . '(\d+)/', $foo, $matches);
$size = (int) $matches[1];
$foo = str_replace($key . $size, $key . ($size * 2), $foo);
can you please used this code :
<?php
$foo = 'height:200px;color:#CCC;font-size:12px';
$styleArr = explode(";",$foo);
$newStyleArr = array();
foreach ($styleArr as $style) {
$explode_str = explode(":",$style);
if($explode_str[0]=="font-size" && count($explode_str)>0) {
$explode_str[1] = str_replace("px","",$explode_str[1]);
$explode_str[1] = ($explode_str[1]*2)."px;";
}
$newStyleArr[] = implode(":",$explode_str);
}
echo implode(";",$newStyleArr);
?>
OUTPUT :
height:200px;color:#CCC;font-size:24px;

Array Exploding and matching per line / Using table Row

Hello can u give me the right code for this one...
$split_getCreatedfield = explode(",", "3,1,2");
$fieldsWithValue = explode("~","1->Samuel Pulta~2->21~3->Male~");
for($row=0;$row<count(fieldsWithValue);$row++){
$data = explode("->", $fieldsWithValue[$row]);
}
I want the output like this one
3 = 3 = Male
2 = 2 = 21
1 = 1 = Samuel Pulta
<?php
$split_getCreatedfield = explode(",", "3,1,2");
$fieldsWithValue = explode("~","1->Samuel Pulta~2->21~3->Male~");
$result = array();
foreach($fieldsWithValue as $key => $val){
if(trim($val) != ""){
$res = explode("->",$val);
$res_key = array_search($res[0],$split_getCreatedfield);
$result[$key][] = $split_getCreatedfield[$res_key];
$result[$key][] = $res[0];
$result[$key][] = $res[1];
}
}
krsort($result); /// Not really required
echo "<table>";
foreach($result as $vals){
echo "<tr><td>".$vals[0]."</td><td>=".$vals[1]."</td><td>=".$vals[2]."</td></tr>";
}
echo "</table>";
?>
output:
3 =3 =Male
2 =2 =21
1 =1 =Samuel Pulta
I would rather use preg_match_all(), like this:
$i = '3,2,1';
$s = '1->Samuel Pulta~2->21~3->Male~';
preg_match_all('/(\d+)->(.*?)(?:~|$)/', $s, $matches);
$fields = array_combine($matches[1], $matches[2]);
foreach (explode(',', $i) as $index) {
if (isset($fields[$index])) {
echo $index, ' = ', $index, ' = ', $fields[$index]. PHP_EOL;
}
}
The regular expression matches items like 1->Samuel Pulta and builds an array with the number as the key and whatever comes after it as the value.
Then, you simply iterate over the necessary indices and print their corresponding value from the $fields array.

How can i explode the string with , and |

How can i explode this? mars#email.com,123,12,1|art#hur.com,321,32,2
the output should be :
$email = mars#email.com
$score = 123
$street = 12
$rank = 1
then remove the |
$email = art#hur.com
$score = 321
$street = 32
$rank = 2
$string = mars#email.com,123,12,1|art#hur.com,321,32,2
explode( ',', $string );
is that correct?
foreach(explode('|', $str) as $v){
$data = explode(',',$v);
echo '$email = '.$data[0].
'$score = '.$data[1].
'$street = '.$data[2].
'$rank = '.$data[3];
}
You might want to use strtok() rather than explode().
http://www.php.net/manual/en/function.strtok.php
$arr = preg_split( '"[,|]"', 'mars#email.com,123,12,1|art#hur.com,321,32,2' );
$len = count($arr);
for( $i = 0; $i < $len; $i+=4 ) {
$email = $arr[$i];
$score = $arr[$i+1];
$street = $arr[$i+2];
$rank = $arr[$i+3];
}
you need to store the new array in variable >
$arr = explode(',',$string);
and I dont get what you want to do with the second part (after the |), but you can get the first par by doing this > $half = explode('|',$string)[0];
You need to unravel it in the right order:
first the blocks separated by |
then individual cells separated by ,
A concise way to do so is:
$array = array_map("str_getcsv", explode("|", $data));
Will give you a 2D array.
Use strtok and explode.
$tok = strtok($string, "|");
while ($tok !== false) {
list($email, $score, $street, $rank) = explode(',', $tok);
$tok = strtok(",");
}
I think what you want is something like this
$output = array();
foreach (explode('|', $string) as $person) {
$output[] = array(
'email' => $person[0],
'score' => $person[1],
'street' => $person[2],
'rank' => $person[3]
)
}
This stores all the results in a multidimensional array. For example, to print person 1's email, you'd use
echo $output[0]['email']; // mars#email.com
and to access person 2's street, you'd use
echo $output[1]['street']; // 32

Categories