My string is like the following format:
$string =
"name=xxx&id=11&name=yyy&id=12&name=zzz&id=13&name=aaa&id=10";
I want to split the string like the following:
$str[0] = "name=xxx&id=11";
$str[1] = "name=yyy&id=12";
$str[2] = "name=zzz&id=13";
$str[3] = "name=aaa&id=10";
how can I do this in PHP ?
Try this:
$matches = array();
preg_match_all("/(name=[a-zA-Z0-9%_-]+&id=[0-9]+)/",$string,$matches);
$matches is now an array with the strings you wanted.
Update
function get_keys_and_values($string /* i.e. name=yyy&id=10 */) {
$return = array();
$key_values = split("&",$string);
foreach ($key_values as $key_value) {
$kv_split = split("=",$key_value);
$return[$kv_split[0]] = urldecode($kv_split[1]);
}
return $return;
}
$string = "name=xxx&id=11&name=yyy&id=12&name=zzz&id=13&name=aaa&id=10";
$arr = split("name=", $string);
$strings = aray();
for($i = 1; $i < count($arr), $i++){
$strings[$i-1] = "name=".substr($arr[$i],0,-1);
}
The results will be in $strings
I will suggest using much simpler term
Here is an example
$string = "name=xxx&id=11;name=yyy&id=12;name=zzz&id=13;name=aaa&id=10";
$arr = explode(";",$string); //here is your array
If you want to do what you asked, nothing more or less , that's explode('&', $string).
If you have botched up your example and you have a HTTP query string then you want to look at parse_str().
Related
Below is a function that can get a string with two other strings without a problem,
function GetBetween($content,$start,$end){
$r = explode($start, $content);
if (isset($r[1])){
$r = explode($end, $r[1]);
return $r[0];
}
return '';
}
Let's say I have code like this:
<code>Sample one</code>
<code>Sample two</code>
<code>Sample three</code>
When using GetBetween($content,'<code>',</code>') Instead of returning something like array("Sample one","Sample two","Sample three") it will only return the first one which is "Sample one"
How can I get it to return EVERYTHING between the two things I specify? I would appreciate it if I could get a solution that isn't hardcoded with the "" tags because I will be needing this for many different things.
Firstly regex is not the correct tool for parsing HTML/XML instead you can simply use DOMDocument like as
$xml = "<code>Sample one</code><code>Sample two</code><code>Sample three</code>";
$dom = new DOMDocument;
$dom->loadHTMl($xml);
$root = $dom->documentElement;
$code_data = $root->getElementsByTagName('code');
$code_arr = array();
foreach ($code_data as $key => $value) {
$code_arr[] = $value->nodeValue;
}
print_r($code_arr);
Output:
Array
(
[0] => Sample one
[1] => Sample two
[2] => Sample three
)
I've had to use a function like this, so I keep it handy:
//where a = content, b = start, c = end
function getBetween($a, $b, $c) {
$y = explode($b, $a);
$len = sizeof($y);
$arr = [];
for ($i = 1; $i < $len; $i++)
$arr[] = explode($c, $y[$i])[0];
return $arr;
}
Anything beyond this, you'll need to start using DomDocument.
Guess you could try something like this,
function GetBetween($content,$tagname){
$pattern = "#<\s*?$tagname\b[^>]*>(.*?)</$tagname\b[^>]*>#s";
preg_match($pattern, $string, $matches);
unset($matches[0]);
return $matches;
}
$content= "<code>Sample one</code><code>Sample two</code><code>Sample three</code>";
//The matching items are:
print_r(GetBetween($content, 'code'));
I'm trying to replace a string which contains value with operator : like "2456:72" to "2456.72" where data is fetched from mysql, I tried using str_replace which sucks. $row_loop3["Tot_minutes"] is the row which I should replace the character, please find my code:
$mysqli = new mysqli("172.16.10.102", "******", "RND#ISO-3306", "eTrans");
if (!$mysqli->multi_query("call sp_get_Android_Online_minutes_Chart ('2015-01-01','2016-01-30')")) {
$response["success"] = 0;
}
do {
if ($res_loop3 = $mysqli->store_result()) {
$response_loop3["minutes"] = array();
$find = ":";
$re = ".";
while ($row_loop3 = $res_loop3->fetch_assoc()) {
$j = 5;
$value_loop3 = array();
$value_loop3["File_Day"] = $row_loop3["edit_date"];
$value_loop3["File_Minutes"] = $row_loop3["FileDay"];
$val["Tot1_Minutes"] = $row_loop3["Tot_minutes"];
$value_loop3["Total_Minutes"] = str_replace($val, $find, $re); //value which I should replace : with .
array_push($response_loop3["minutes"], $value_loop3);
$response_loop3["success"] = 1;
}
echo $merger = json_encode(array_merge($response, $response_loop2, $response_loop3));
$res->free();
}
} while ($mysqli->more_results() && $mysqli->next_result());
please help me, thanks in advance
You are not making variable instead you are making associative array.
change this
$val["Tot1_Minutes"] = $row_loop3["Tot_minutes"];
to
$val= $row_loop3["Tot_minutes"];
and also order in str function to
$val = $row_loop3["Tot_minutes"];
$value_loop3["Total_Minutes"]=str_replace($find,$re,$val);
str_replace should be used in this way:
str_replace( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
The function's argument are search, replace, and subject, so for your case should be like : str_replace($find,$re,$val)
I have the following text string: "Gardening,Landscaping,Football,3D Modelling"
I need PHP to pick out the string before the phrase, "Football".
So, no matter the size of the array, the code will always scan for the phrase 'Football' and retrieve the text immediately before it.
Here is my (lame) attempt so far:
$array = "Swimming,Astronomy,Gardening,Rugby,Landscaping,Football,3D Modelling";
$find = "Football";
$string = magicFunction($find, $array);
echo $string; // $string would = 'Landscaping'
Any help with this would be greatly appreciated.
Many thanks
$terms = explode(',', $array);
$index = array_search('Football', $terms);
$indexBefore = $index - 1;
if (!isset($terms[$indexBefore])) {
trigger_error('No element BEFORE');
} else {
echo $terms[$indexBefore];
}
//PHP 5.4
echo explode(',Football', $array)[0]
//PHP 5.3-
list($string) = explode(',Football', $array);
echo $string;
$array = array("Swimming","Astronomy","Gardening","Rugby","Landscaping","Football","3D" "Modelling");
$find = "Football";
$string = getFromOffset($find, $array);
echo $string; // $string would = 'Landscaping'
function getFromOffset($find, $array, $offset = -1)
{
$id = array_search($find, $array);
if (!$id)
return $find.' not found';
if (isset($array[$id + $offset]))
return $array[$id + $offset];
return $find.' is first in array';
}
You can also set the offset to be different from 1 previous.
I have a variable that contains text with values according to an example below:
$data = "5:7|4:1|504:2|1:3|"
And I would like to achieve results like this:
$data[5] = 7;
$data[4] = 1;
$data[504] = 2;
$data[1] = 3;
I tried with explode:
$data = explode("|", $data);
//but it makes $data[0]="5:7"; $data[1]="4:1"; and so on.
Should I use explode again? Is it has any sense, or is there another way? I would like to ask for a hint or help.
There may be a more clever way, but I'd do it like this:
$data = array();
foreach (explode("|", $your_data) as $part)
{
$pieces = explode(':', $part);
// Assumes we have 2 pieces, might want to make sure here...
$data[$pieces[0]] = $pieces[1];
}
Also, I'm not sure what this data represents but keep in mind that array keys will overwrite each other, so 1:1|1:2 will result in an array with only one item (the last piece). There may be good reason to take another approach.
Sure, explode again:
$data = "5:7|4:1|504:2|1:3";
$array = array();
foreach (explode('|', $data) as $pair) {
list($id, $val) = explode(':', $pair);
$array[$id] = $val;
}
Yes you should use explode twice, like this
$newData = array();
$pairs = explode('|',$data);
foreach($pairs as $pair){
$tmp = explode(':',$pair);
$newData[$tmp[0]] = $tmp[1];
}
Try using a regexp:
$data = preg_split ("\||:", $data);
One line version:
$data = array_map(function($d) { return (int)explode(":", $d)[1]; }, explode("|", $data));
I am using an api to retrieve data from another server the data returned is something like this:
accountid=10110 type=prem servertime=1263752255 validuntil=1266163393
username= curfiles=11 curspace=188374868 bodkb=5000000 premkbleft=24875313
This is a whole string I need two values out of whole string, I am currently using preg_match to get it, but just to learn more and improve my coding is there any other way or function in which all values are automatically convert to array?
Thank You.
Sooo, my faster-than-preg_split, strpos-based function looks like this:
function unpack_server_data($serverData)
{
$output = array();
$keyStart = 0;
$keepParsing = true;
do
{
$keyEnd = strpos($serverData, '=', $keyStart);
$valueStart = $keyEnd + 1;
$valueEnd = strpos($serverData, ' ', $valueStart);
if($valueEnd === false)
{
$valueEnd = strlen($serverData);
$keepParsing = false;
}
$key = substr($serverData, $keyStart, $keyEnd - $keyStart);
$value = substr($serverData, $valueStart, $valueEnd - $valueStart);
$output[$key] = $value;
$keyStart = $valueEnd + 1;
}
while($keepParsing);
return $output;
}
It looks for an equals character, then looks for a space character, and uses these two to decide where a key name begins, and when a value name begins.
Using explode is the fastest for this, no matter what.
However, to answer you question, you can do this many ways. But just because you can, doesn't mean you should. But if you really wanna make it weird, try this.
UPdated using strpos
$arr = array();
$begin = 0;
$str = trim($str); # remove leading and trailing whitespace
while ($end = strpos($str, ' ', $begin)) {
$split = strpos($str, '=', $begin);
if ($split > $end) break;
$arr[substr($str, $begin, $split-$begin)] = substr($str, $split+1, $end-$split-1);
$begin = $end+1;
}
try out parse_str maybe you need to do str_replace(' ', '&', $string); before