how to explode following string - php

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);
?>

Related

First word of a comma separated sentence php

My string is : Hi my, name is abc
I would like to output "Hi Name".
[Basically first word of comma separated sentences].
However sometimes my sentence can also be Hi my, "name is, abc"
[If the sentence itself has a comma then the sentence is enclosed with ""].
My output in this case should also be "Hi Name".
So Far I've done this
$str = "hi my,name is abc";
$result = explode(',',$str); //parsing with , as delimiter
foreach ($result as $results) {
$x = explode(' ',$results); // parsing with " " as delimiter
forach($x as $y){}
}
You can use explode to achieve YOUR RESULT and for IGINORE ' OR " use trim
$str = 'hi my,"name is abc"';
$result = explode(',',$str); //parsing with , as delimiter
$first = explode(' ',$result[0]);
$first = $first[0];
$second = explode(' ',$result[1]);
$second = trim($second[0],"'\"");
$op = $first." ".$second;
echo ucwords($op);
EDIT or if you want it for all , separated values use foreach
$str = 'hi my,"name is abc"';
$result = explode(',',$str); //parsing with , as delimiter
$op = "";
foreach($result as $value)
{
$tmp = explode(' ',$value);
$op .= trim($tmp[0],"'\"")." ";
}
$op = rtrim($op);
echo ucwords($op);
Basically it's hard to resolve this issue using explode, str_pos, etc. In this case you should use state machine approach.
<?php
function getFirstWords($str)
{
$state = '';
$parts = [];
$buf = '';
for ($i = 0; $i < strlen($str); $i++) {
$char = $str[$i];
if ($char == '"') {
$state = $state == '' ? '"' : '';
continue;
}
if ($state == '' && $char == ',') {
$_ = explode(' ', trim($buf));
$parts[] = ucfirst(reset($_));
$buf = '';
continue;
}
$buf .= $char;
}
if ($buf != '') {
$_ = explode(' ', trim($buf));
$parts[] = ucfirst(reset($_));
}
return implode(' ', $parts);
}
foreach (['Hi my, "name is, abc"', 'Hi my, name is abc'] as $str) {
echo getFirstWords($str), PHP_EOL;
}
It will output Hi Name twice
Demo

How to splitt a string to an array with keys and values using php

I have string and I want to splitt it to array and remove a specific part and then convert it back to a string .
$string = "width,100;height,8600;block,700;narrow,1;"
I want to search block in this string and remove it with its value "block,700;" and get the string as "width,100;height,8600;narrow,1;"
below is my code php which i tried.Please advice me
$outerARR = explode(";", $string);
$arr = array();
foreach ($outerARR as $arrvalue) {
$innerarr = explode(",", $arrvalue);
$arr[] = $innerarr;
}
for ($i = 0; $i < count($arr); $i++) {
if (in_array($arr, 'block')) {
unset($arr[$i]);
}
}
Please note that "block" in aboive string will not always contain and the value may differ. So I can't use string replace . please advice
You essentially want to replace part of your string:
$string = "width,100;height,8600;block,700;narrow,1;";
$regex = '#(block,(.*?);)#';
$result = preg_replace($regex, '', $string);
echo $result;
Try this:
$string = "width,100;height,8600;block,700;narrow,1;"
$outerARR = explode(";", $string);
$arr = array();
foreach ($outerARR as $arrvalue) {
$innerarr = explode(",", $arrvalue);
$arr[$innerarr[0]] = $innerarr[1];
}
if (array_key_exists('block', $arr)) {
unset($arr['block']);
}

PHP - str_replace not working

I am trying to remove a list of words, which I have contained in a .txt, from a file. To do this I am reading both files using file_get_contents into strings and using str_replace.
$names = file_get_contents("countries.txt");
$map = file_get_contents("C:\\xampp\\htdocs\\www\\jvectormap\\map\\worldmap.js");
$array = explode("\n", $names);
foreach($array as $val){
$split = explode(" ", $val);
$max = count($split);
$country = "";
for($x = 1; $x < $max; $x++){
$country = $country . $split[$x];
if($x < ($max-1)){
$country = $country . " ";
}
}
$map = str_replace($country, "", $map);
}
echo $map;
The "countries.txt" contains the countries in this format:
AD Andorra
BE Belize
etc.
..which is why I am using explode() to strip the country tag.
When I echo $map the string contains all the countries even thought str_replace hasn't thrown an error. I have tried printing out $country to confirm it's reading the countries correctly along with reading it into an array and then looping through the array, using str_replace.
I think you need some modification in code
change below line
$array = explode("\n", $names);
to with these
$names = nl2br($names);
$array = explode("<br />", $names);
As you are working on window which uses \r\n for new line.
Cannot reproduce.
<?php
/* Instead of loading countries.txt */
$names = "AD Andorra
BE Belize";
$array = explode("\n", $names);
/* Instead of loading map */
$map = "Andorra Belize";
$array = explode("\n", $names);
foreach($array as $val){
$split = explode(" ", $val);
$max = count($split);
$country = "";
for($x = 1; $x < $max; $x++){
$country = $country . $split[$x];
if($x < ($max-1)){
$country = $country . " ";
}
}
$map = str_replace($country, "", $map);
}
var_dump($map);
Output:
string(1) " "
The space is expected, if you want to get rid of it use trim(). However, the replacement is working fine, if it still doesn't work your text files might be the problem.

Implode with array with keys in PHP

I need to write an array to a .csv file in PHP.
Example array:
$array = array(
"name" => "John",
"surname" => "Doe",
"email" => "nowhere#nowhere.com"
);
By using implode(",", $array), I get a result like this:
John,Doe,nowhere#nowhere.com
However, I need to also write the key of each element to the file.
The desired output is this:
name:John,surname:Doe,email:nowhere#nowhere.com
How would I achieve this?
Try this code:
$out = $sep = '';
foreach( $array as $key => $value ) {
$out .= $sep . $key . ':' . $value;
$sep = ',';
}
$csv = "";
foreach($array as $key => $data)
{
// be sure to add " in your csv
$csv .= '"'.$key.':'.$data.'",';
}
// and add a new line at the end
$csv .= "\n";
echo $csv;
The answers above outputs a trailing comma at the end. To correct this, I use the following function:
$array = array(
"name" => "John",
"surname" => "Doe",
"email" => "nowhere#nowhere.com"
);
function implodeKV($glueKV, $gluePair, $KVarray){
$t = array();
foreach($KVarray as $key=>$val) {
$t[] = $key . $glueKV . $val;
}
return implode($gluePair, $t);
}
echo implodeKV( ':' , ',' , $array);
// outputs name:John,surname:Doe,email:nowhere#nowhere.com
http://phpassist.com/2dde2#2
If you're using PHP 5.3+, then an anonymous function can make your code a lot cleaner, though a simple for loop has the best performance. (Using array_walk comes close though!)
I ran some tests with a few different approaches (using PHP 5.4.33):
function makeArray(&$a) {
$a = array();
for($i = 0; $i < 100000; $i++) {
$a[rand()] = rand();
}
return $a;
}
makeArray($array);
$before = microtime(true);
$result = implode(
",",
array_map(
function($k, $v) {
return "$k:$v";
},
array_keys($array),
$array
)
);
$after = microtime(true);
$dur = $after - $before;
echo "Array Map w/ anonymous function: {$dur}s<br>";
makeArray($array);
$before = microtime(true);
function kv_func($k, $v) {
return "$k:$v";
}
$result = implode(
",",
array_map(
"kv_func",
array_keys($array),
$array
)
);
$after = microtime(true);
$dur = $after - $before;
echo "Array Map w/ function: {$dur}s<br>";
makeArray($array);
$before = microtime(true);
array_walk(
$array,
function(&$v, $k) {
$v = "$k:$v";
}
);
$result = implode(
",",
$array
);
$after = microtime(true);
$dur = $after - $before;
echo "Array Walk w/ anonymous function: {$dur}s<br>";
makeArray($array);
$before = microtime(true);
$ff = true;
$sep = ",";
$out = "";
foreach($array as $key => $val) {
if($ff) $ff = false;
else $out .= $sep;
$out .= "$key:$val";
}
$after = microtime(true);
$dur = $after - $before;
echo "Foreach loop w/ loop flag: {$dur}s<br>";
makeArray($array);
$before = microtime(true);
$out = "";
foreach($array as $key => $val) {
$out .= "$key:$val,";
}
$out = substr($out, 0, -1);
$after = microtime(true);
$dur = $after - $before;
echo "Foreach loop + substr: {$dur}s<br>";
Results:
Array Map w/ anonymous function: 0.13117909431458s
Array Map w/ function: 0.13743591308594s // slower than anonymous
Array Walk w/ anonymous function: 0.065797805786133s // close second
Foreach loop w/ loop flag: 0.042901992797852s // fastest
Foreach loop + substr: 0.043946027755737s // comparable to the above
And just for kicks, I tried the for loop without correcting for the trailing comma. It didn't really have any impact:
Foreach loop w/ trailing comma: 0.044748067855835s
<?php
$array = array(
"name" => "John",
"surname" => "Doe",
"email" => "nowhere#nowhere.com"
);
foreach( $array as $key=>$data ) {
$output .= $comma . $key . ':' . $data;
$comma = ',';
}
echo $output;
?>

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