How can i explode the string with , and | - php

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

Related

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.

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 split data from string in 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");

how to explode array within array in php

i have an array contain value like :
Check_Value ('level_codes', '1000', '1001','(1000,1002,1004)', 'DO ', '1')==1
i want to get values and store into an other parametrs like :
$codes = level_codes;
$first_value = 1000;
$second_value = 1001;
$list_values = (1000,1002,1004);
$action = DO;
$timer = 1;
$case = ==;
$status = 1;
is there any one please help me to do this work...!
Use the list() function: http://php.net/list
If the order is always the same, the following will reassign the values to the variables you want:
$parts = preg_split("/'?\(|\)'?/", $original_values);
$sub1 = explode(',', $parts[1]);
$codes = trim(str_replace("'", '', $sub1[0])) ;
$first_value = trim(str_replace("'", '', $sub1[1]));
$second_value = trim(str_replace("'", '', $sub1[2]));
$list_values = "($parts[2])";
$sub2 = explode(',', $parts[3]);
$action = trim(str_replace("'", '', $sub2[1]));
$timer = trim(str_replace("'", '', $sub2[2]));
preg_match('/(\D+)(\d+)/', $parts[4], $matches);
$case = $matches[1];
$status = $matches[2];
There might be a more elegant way to do it, but the original value is a string, rather than an array.
If the array is string, i think you should look into preg_match

Categories