I have to extract a string like this:
index.php?module=Reports&action=abc&rname=Instantpayment
Now my task is to extract report, action and rname value in PHP.
I have tried by using explode(), but I am not able to extract module.
How can I do it?
You could use parse_str() in this case:
$string = 'index.php?module=Reports&action=abc&rname=Instantpayment';
$string = substr($string, strpos($string, '?')+1); // get the string from after the question mark until end of string
parse_str($string, $data); // use this function, stress free
echo '<pre>';
print_r($data);
Should output:
Array
(
[module] => Reports
[action] => abc
[rname] => Instantpayment
)
$yourUrl="module=Reports&action=abc&rname=Instantpayment"
$exploded_array = array();
parse_str($yourUrl, $exploded_array);
$exploded_array['module'];
$exploded_array['action'];
$exploded_array['rname'];
Use $_GET to get query strings from the URL
echo $_GET['module']; //Reports
echo $_GET['action']; // abc
echo $_GET['rname']; // Instantpayment
For getting from the string try explode():
$str ='index.php?module=Reports&action=abc&rname=Instantpayment';
$e = explode('?', $str);
$e1 = explode('&', $e[1]);
foreach($e1 as $v) {
$ex = explode('=', $v);
$newarr[$ex[0]] = $ex[1];
}
print_r($newarr); // Use this array of values you want.
//Array ( [module] => Reports [action] => abc [rname] => Instantpayment )
echo $newarr['module'];
echo $newarr['action'];
echo $newarr['rname'];
You have to access the globale GET variable:
$_GET['module']
$_GET['action']
$_GET['rname']
Try this:
<?php
$temp = "index.php?module=Reports&action=abc&rname=Instantpayment";
$t1 = explode("=",$temp);
for ($i = 1; $i < sizeof($t1); $i++)
{
$temp = explode("&", $t1[$i]);
echo $temp[0] . "\n";
}
?>
Related
i have a text result from database like this:
var1=value1&var2=value2&var3=value3
How to convert into a variable and get the value?
$str = "var1=value1&var2=value2&var3=value3";
parse_str($str, $output);
print_r($output);
Array
(
[var1] => value1
[var2] => value2
[var3] => value3
)
manual page:http://php.net/manual/en/function.parse-str.php
This works too:
<?php
$string = "var1=value1&var2=value2&var3=value3";
$string = explode("&", $string);
foreach($string as $key) {
$result = strrchr($key,"=");
$result = trim($result, "=");
echo $result . "<br>";
}
?>
I am trying to make use of files(.txt) to print logs. Inside the file, it logs an array value which looks like this:
Array
(
[NAME] => John Peters
[AGE] => 24
[COUNTRY] => United States
[EMAIL] => test#test.com
)
So now, I am trying to read the file contents and covert it onto an actual array so that I would be able to reference the value using the array key in a php file, something like:
echo 'Name : ' .$person['NAME'];
echo 'Age: ' .$person['AGE'];
echo 'Country: ' .$person['COUNTRY'];
echo 'Email: ' .$person['EMAIL'];
Is there a predefined php function to do it? Or how will I be able to accomplish what I want. I have tried to use the fread() and fgets() function but it doesn't really accomplish what I want or I might be missing something.
I wrote a quick script for you,
I assumed that in your (files).txt can contain many entries of print_r results e.g.
Array
(
[NAME] => John Peters
[AGE] => 24
[COUNTRY] => United States
[EMAIL] => test#test.com
)
Array
(
[NAME] => John Peters
[AGE] => 24
[COUNTRY] => United States
[EMAIL] => test#test.com
)
This script assumes that your inputs test.txt only contains array that has 1 level (so, it won't work with nested array)
$c = file_get_contents('test.txt');
# Matches all strings that has 'Array(...)' pattern
preg_match_all('#Array[^\)]+\)#', $c, $matches);
$items = array();
foreach($matches[0] as $match) {
# Extracts KEY => VAL patterns from matched text
if (preg_match_all('#\[([^\]]+)\].*?>(.*)#', $match, $array)) {
$items[] = array_combine($array[1], $array[2]);
}
}
# test your results
print_r($items);
you can read it using file_get_contents
Eg:
<?php
$homepage = file_get_contents('abc.txt');
echo $homepage;
?>
Hope it will help :)
I guess #Rezigned and I had the same idea... Here's what I came up with:
<?php
$file = file_get_contents('log.txt');
$file = preg_match_all('/(\s+\[[a-zA-Z0-9]+\]\s+=>\s+.+)\n/', $file, $lines);
$key = array();
$val = array();
foreach ($lines[0] as $line) {
$keys_vals = preg_split('/(\s+=>\s+)/', $line);
$key[] .= preg_replace('/[\[|\]]/', '', $keys_vals[0]);
$val[] .= $keys_vals[1];
}
$line_count = count($lines[0]);
for ($i = 0; $i < $line_count; $i++) {
print $key[$i] . ': ' . $val[$i];
}
There is a function shared by Matt in PHP manual called print_r_reverse, I think it's what you want. The following code is copied from PHP manual print_r function comments section directly.
<?php
function print_r_reverse($in) {
$lines = explode("\n", trim($in));
if (trim($lines[0]) != 'Array') {
// bottomed out to something that isn't an array
return $in;
} else {
// this is an array, lets parse it
if (preg_match("/(\s{5,})\(/", $lines[1], $match)) {
// this is a tested array/recursive call to this function
// take a set of spaces off the beginning
$spaces = $match[1];
$spaces_length = strlen($spaces);
$lines_total = count($lines);
for ($i = 0; $i < $lines_total; $i++) {
if (substr($lines[$i], 0, $spaces_length) == $spaces) {
$lines[$i] = substr($lines[$i], $spaces_length);
}
}
}
array_shift($lines); // Array
array_shift($lines); // (
array_pop($lines); // )
$in = implode("\n", $lines);
// make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $in, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
$pos = array();
$previous_key = '';
$in_length = strlen($in);
// store the following in $pos:
// array with key = key of the parsed array's item
// value = array(start position in $in, $end position in $in)
foreach ($matches as $match) {
$key = $match[1][0];
$start = $match[0][1] + strlen($match[0][0]);
$pos[$key] = array($start, $in_length);
if ($previous_key != '') $pos[$previous_key][1] = $match[0][1] - 1;
$previous_key = $key;
}
$ret = array();
foreach ($pos as $key => $where) {
// recursively see if the parsed out value is an array too
$ret[$key] = print_r_reverse(substr($in, $where[0], $where[1] - $where[0]));
}
return $ret;
}
}
I generate an array with URL's from a webpage with file_get_contents, that i want to remove entry's (key & value) from if they contain specific data.
For example:
[0] = 'http://somesite.com'
[1] = 'http://someothersite.com/article/id/55/file.pdf'
[2] = 'http://someothersite.com/article/id/56/file2.pdf'
[3] = 'javascript:void(0)'
[4] = 'mailto:info#somesite.com'
I want to remove the entry's
http://somesite.com
javascript:void(0)
mailto:info#somesite.com
Because i only need the URL's with the .pdf files.
How do i do that?
You can use array filter for this (note this syntax works for php 5.3+)
$filtered = array_filter($array, function ($a){ return preg_match ('/.pdf$/', $a); });
Hopefully this will help:
$sites[0] = 'http://somesite.com';
$sites[1] = 'http://someothersite.com/article/id/55/file.pdf';
$sites[2] = 'http://someothersite.com/article/id/56/file2.pdf';
$sites[3] = 'javascript:void(0)';
$sites[4] = 'mailto:info#somesite.com';
echo '<pre>'.print_r($sites, true).'</pre>';
//loop through your array of items/sites
foreach($sites as $key=>$value){
//remove whitespace
$value = trim($value);
//get last 4 chars of value
$ext = substr($value, -4, 0);
//check if it is not .pdf
if($ext != '.pdf'){
//unset item from array
unset($sites[$key]);
}
}
echo '<pre>'.print_r($sites, true).'</pre>';
$array = array('http://somesite.com','http://someothersite.com/article/id/55/file.pdf','http://someothersite.com/article/id/56/file2.pdf','javascript:void(0)','mailto:info#somesite.com');
for($i=0; $i<=count($array)+1 ; $i++)
{
if(end(explode('.',$array[$i])) != "pdf" )
{
unset($array[$i]);
}
}
Try this !!!!
$haystack = array (
'0' => 'http://somesite.com',
'1' => 'http://someothersite.com/article/id/55/file.pdf',
'2' => 'http://someothersite.com/article/id/56/file2.pdf',
'3' => 'javascript:void(0)',
'4' => 'mailto:info#somesite.com'
);
$matches = preg_grep ('/pdf/i', $haystack);
//print_r ($matches);
foreach($matches as $k=>$v):
echo $matches[$k]."<br/>";
endforeach;
Documentation
preg_grep
array_filter is always an option, but if you want to remove specific values another good candidate is array_diff:
$remove = [
'http://somesite.com',
'javascript:void(0)',
'mailto:info#somesite.com',
];
$filtered = array_diff($array, $remove);
Question
i have string like this $str="a|apple||b|bat||c|cat||d|dog";
from the above string i want to create a array dynamically n that newly created array shud look like this Array
(
[a] => apple
[b] => bat
[c] => cat
[d] => dog
)
Question
i have html string like this
$html_string="<div>Content Div1</div>
<div>Content Div2</div>
<div>Content Div3</div>";
how can i get 3rd DIV ,resulting answer should be like this
$ans="<div>Content Div3</div>" ;
Please anyone help me
for the first one
$str = "a|apple||b|bat||c|cat||d|dog";
$new_array = array();
$my_array = explode("||", $str);
$my_array = array_filter($my_array);
foreach ($my_array as $mine) {
$my = explode("|", $mine);
$new_array[$my[0]] = $my[1];
}
print_r($new_array);
// Output
Array
(
[a] => apple
[b] => bat
[c] => cat
[d] => dog
)
**for second**
$html_string = "<div>Content Div1</div><div>Content Div2</div><div>Content Div3</div>";
$new_arr = explode("</div>", $html_string);
$my_data = $new_arr[2] . '</div>';
print_r($my_data);
// Output
<div>Content Div3</div>
Try this:
First
$str = "a|apple||b|bat||c|cat||d|dog";
$my_array = explode("||", $str);
$finalArr=array();
foreach($my_array as $my_arr)
{
$myar = explode("|", $my_arr);
$finalArr[$myar[0]]=$myar[1];
}
print_r($finalArr);
For Second
$html_string="<div>Content Div1</div><div>Content Div2</div><div>Content Div3</div>";
$secondArray = explode('</div>', $html_string);
echo $res = $secondArray[2] . "</div>";
Test it on http://writecodeonline.com/php/
try this:
1st Answer:
<?php
$str="a|apple||b|bat||c|cat||d|dog";
$parentArray = explode('||', $str);
$finalArray = array();
foreach($parentArray as $parentKey=>$parentValue)
{
$childArray = explode('|', $parentValue);
$finalArray[$childArray[0]] = $childArray[1];
}
echo "<pre>";
print_r($finalArray);
?>
2nd Answer
<?php
$html_string="<div>Content Div1</div>
<div>Content Div2</div>
<div>Content Div3</div>";
$finalArray = explode('</div>', $html_string);
$resultRequired = $finalArray[2] . "</div>";
?>
For your first question:
$tmp_array = explode( '||', $str );
$str_array = array();
foreach( $tmp_array as $value ){
$tmp = explode( '|', $value );
$str_array[ $tmp[0] ] = $tmp[1];
}
For your second question
$html_array = array();
$pattern = '/\<div\>.*\<\/div\>/i';
if( preg_match_all( $pattern, $html_string, $matches ) ) {
$html_array = $matches[0];
}
Which will make:
<div>Content Div3</div>
Be in $html_array[2] if any matches are found.
I have following records in text file, need to extract that record form text file and treat them as seperate array variables
r1=(1,2,3)|r2=(4,5,6)|r3=(1,2,3,4,5,7)|rn=(9,6,7,8) seperated by pipe(|)
I need to represent that as array use seperately like below
$r1= Array
(
[0] => 1
[1] => 2
[2] => 3
)
$r2=Array
(
[0] => 4
[1] => 5
[2] => 6
)
I have no idea how to do it, is it possible in php?
Just a plain regular expression to break up the string, followed by an explode on each group:
if (preg_match_all('#(\w+)=\(([\d,]*)\)#', $s, $matches)) {
foreach ($matches[2] as $i => $groups) {
$group_name = $matches[1][$i];
$$group_name = array_map('intval', explode(',', $groups));
}
}
print_r($r1);
print_r($r3);
print_r($rn);
You can use Eval
//Assuming you can pull the content from text file using fread
$temp = "r1=(1,2,3)|r2=(4,5,6)";
$temp=str_replace("=","=array",$temp);
$split=explode("|",$temp);
echo "<pre>";
foreach($split as $k=>$v){
$v="$".$v.";";
//Evaluate a string as PHP code .i.e You will get r1,r2 as a variable now which is array
eval($v);
}
print_r($r1);
print_r($r2);
$data = "r1=(1,2,3)|r2=(4,5,6)|r3=(1,2,3,4,5,7)|rn=(9,6,7,8)";
$arr = explode("|", $data);
$finArray = array();
foreach($arr as $key=>$value)
{
$single = explode('(', $value);
$finArray[] = explode(',', str_replace(')', '', $single[1]));
}
print_r($finArray);
can be done as:
$string="r1=(1,2,3)|r2=(4,5,6)|r3=(1,2,3,4,5,7)|rn=(9,6,7,8)";
$string=str_repla("r1=","",$string);
$yourArray=explode('|', $string);
This code will help you:--
<?php
$file = "/tmp/file1.txt"; // this is your file path
$f = fopen($file, "r");
while ( $line = fgets($f, 1000) ) {
print $line;
$a=explode('|',$line);
print_r($a); // I have explode based on | for you...
foreach($a as $key=>$value)
{
print_r($value);
}
fclose($file);
}
?>
""or""
$a="r1=(1,2,3)|r2=(4,5,6)|r3=(1,2,3,4,5,7)|rn=(9,6,7,8)";
$a=explode('|',$a);
print_r($a);
<?php
$file = "file.txt";
$f = fopen($file, "r");
while ( $line = fgets($f, 1000) ) {
$str = $line;
}
$str1 = explode("|",$str);
foreach($str1 as $temp) {
$str2 = explode("=",$temp);
$data[$str2[0]] = explode(",",trim($str2[1],"()"));
}
echo '<pre>';
print_r($data);
echo '</pre>';
?>
This will do your job.