retrieving a parameter from a string - php

index.php?option=com_virtuemart&Itemid=210&category_id=12&lang=is&limit=20&limitstart=180&page=shop.browse
and I would like to retrieve the Page parameter from the string and if that page parameter is equal to "shop.browse" than return a true boolean.
edit: ps. the string does not always look like this but it does always contain the page= parameter
Ive been messing with strpos function and others and I can't get this working and I need this code quickly so if anyone can point me in there right direction of the best approach.
Thanks

Use parse_url first to get just the query part, then use parse_str to get the values:
$query = parse_url($str,PHP_URL_QUERY);
parse_str($query, $match);
if ($match['page'] === 'shop.browse') {
// page=shop.browse
}
Note that this assumes your string is stored in a variable $str.

Check the parse_url() function.

$str = explode("?",$url);
$str = explode("&",$str[1]);
foreach($str as $k=>$v) {
$xxx = explode("=",$v);
$output[$xxx[0]] = $output[$xxx[1]];
}
echo $output["page"];
this way you get all the parameters mapped to their keys. you obtain something like the $_GET/$_POST stuff is rendered.

the whole thing:
<?php
$url = "index.php?option=com_virtuemart&Itemid=210&category_id=12&lang=is&limit=20&limitstart=180&page=shop.browse";
$url = parse_url($url);
parse_str($url['query'], $output);
if($output['page'] == "shop.browse")
{
//stmts
}
else
{
//stmts
}

Related

Using preg_replace on url variables

I have some very long URL variables. Here is one example.
http://localhost/index.php?image=XYZ_1555025022.jpg&mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=no&mode=color&printscalewidth100=&printscaleheight100=&rand=56039
Ultimately it would be nice if I could find a way to use preg_replace to simply change one variable even if in the middle of the string for instance in the string above change print=no to 'print=yes for example.
I will however settle for a preg_replace pattern match that allows me to delete ?image=XYZ_1555025022.jpg. as this is a variable the name could be anything. It will always have "?image" " at the start and end with "&"
I think one of the problems I have run into is that preg_match seems to have issues on strings with "=" contained in them .
I am completely lost here in this and all those characters make may head spin. Maybe someone can give some guidance please?
Here's a demo of how you can do some of things you want using explode, parse_str and http_build_query:
$url = 'http://localhost/index.php?image=XYZ_1555025022.jpg&mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=no&mode=color&printscalewidth100=&printscaleheight100=&rand=56039';
// split on first ?
list($path, $query_string) = explode('?', $url, 2);
// parse the query string
parse_str($query_string, $params);
// delete image param
unset($params['image']);
// change the print param
$params['print'] = 'yes';
// rebuild the query
$query_string = http_build_query($params);
// reassemble the URL
$url = $path . '?' . $query_string;
echo $url;
Output:
http://localhost/index.php?mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=yes&mode=color&printscalewidth100=&printscaleheight100=&rand=56039
Demo on 3v4l.org
You can use str_replace() or preg_replace() to get your job done, but parse_url() with parse_str() will give you more controls to modify any parameters easily by array index. Finally use http_build_query() to make your final url after modification.
<?php
$url = 'http://localhost/index.php?image=XYZ_1555025022.jpg&mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=no&mode=color&printscalewidth100=&printscaleheight100=&rand=56039';
$parts = parse_url($url);
parse_str($parts['query'], $query);
echo "BEFORE".PHP_EOL;
print_r($query);
$query['print'] = 'yes';
echo "AFTER".PHP_EOL;
print_r($query);
?>
DEMO: https://3v4l.org/npGij

Mathematial operations in preg_match

I need to lower preg variable by one. Example:
$code = A4-7;
$new = preg_replace('/A([0-9])\-([0-9])/', 'S($1-1)-$2', $code);
I need to do something like that, so preg replace returns S3-7. Is there some way?
Try this (using preg_replace_callback)
$code = "A4-7";
function myfunc($matches)
{
return 'S'.($matches[1]-1).'-'.$matches[2];
}
echo preg_replace_callback("#A(\d)-(\d)#","myfunc",$code);
You will have to extract the values first, perform the mathematical operations on the extracted values and then reconstruct the string to achieve what you want.
For example:
<?php
$code = 'A4-7';
preg_match('/A([0-9])\-([0-9])/', $code, $matches);
$new = 'S'.($matches[1]-1).'-'.$matches[2];
?>

php how to make a if str_replace?

$str is some value in a foreach.
$str = str_replace('_name_','_title_',$str);
how to make a if str_replace?
I want do the thing if have a str_replace then echo $str, else not, jump the current foreach then to the next. Thanks.
There is a fourth parameter to str_replace() that is set to the number of replacements performed. If nothing was replaced, it's set to 0. Drop a reference variable there, and then check it in your if statement:
foreach ($str_array as $str) {
$str = str_replace('_name_', '_title_', $str, $count);
if ($count > 0) {
echo $str;
}
}
If you need to test whether a string is found within another string, you can like this.
<?php
if(strpos('_name_', $str) === false) {
//String '_name_' is not found
//Do nothing, or you could change this to do something
} else {
//String '_name_' found
//Replacing it with string '_title_'
$str = str_replace('_name_','_title_',$str);
}
?>
http://php.net/manual/en/function.strpos.php
However you shouldn't need to, for this example. If you run str_replace on a string that has nothing to replace, it won't find anything to replace, and will just move on without making any replacements or changes.
Good luck.
I know this is an old question, but it gives me a guideline to solve my own checking problem, so my solution was:
$contn = "<p>String</p><p></p>";
$contn = str_replace("<p></p>","",$contn,$value);
if ($value==0) {
$contn = nl2br($contn);
}
Works perfectly for me.
Hope this is useful to someone else.

Extract number from variable

I have this string:
$guid = 'http://www.test.com/?p=34';
How can I extract the value of get var p (34) from the string and have $guid2 = '34'?
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $vars);
$guid2 = $vars['p'];
If 34 is the only number in the query string, you can also use
echo filter_var('http://www.test.com/?p=34', FILTER_SANITIZE_NUMBER_INT); // 34
This will strip anything not a number from the URL string. However, this will fail the instant there is other numbers in the URL. The solution offered by konforce is the most reliable approach if you want to extract the value of the p param of the query string.
A preg_replace() is probably the quickest way to get that variable, the code below will work if it is always a number. Though konforce's solution is the general way of getting that information from a URL, though it does a lot of work for that particular URL, which is very simple and can be dealt with simply if it unaltering.
$guid = 'http://www.test.com/?p=34';
$guid2 = preg_replace("/^.*[&?;]p=(\d+).*$/", "$1", $guid);
Update
Note that if the URLs can not be guaranteed to have the variable p=<number> in them, then you would need to use match instead, as preg_replace() would end up not matching and returning the whole string.
$guid = 'http://www.test.com/?p=34';
$matches = array();
if (preg_match("/^.*[&?;]p=(\d+).*$/", $guid, $matches)) {
$guid2 = $matches[1];
} else {
$guid2 = false;
}
That is WordPress. On a single post page you can use get_the_ID() function (WP built-in, used in the loop only).
$guid2 = $_GET['p']
For more security:
if(isset($_GET['p']) && $_GET['p'] != ''){
$guid2 = $_GET['p'];
}
else{
$guid2 = '1'; //Home page number
}

list and explode

I am trying to use url rewriting on my website and I want to use the list() and explode() functions to get the right content.
Currently my code looks like this:
list($dir, $act) = explode('/',$url);
In this case $url is equal to everything after the first slash in the absolute url i.e. http://example.com/random/stuff => $url = random/stuff/ this would work fine, but if I want to go to http://example.com/random/ then it will print a notice on the page. How do I stop the notice from showing up do I need to use something other than the list() function?
Right now the notice is "Notice: Undefined offset: 1..."
Thanks for the help!
Try this :
list($dir, $act) = array_pad(explode('/',$url), 2, '');
array_pad complete the array with your values, here is : ''.
You should check how many path segments the URL contains:
$segments = explode('/', $url);
if (count($segments) !== 2) {
// error
} else {
list($dir, $act) = $segments;
}
But maybe you should choose a more flexible approach than using list.
Check out parse_url
A solution would be to split your line of code in several, to ensure you never assign non-existing values to variables -- which is what you are doing when explode only returns one portion of URL.
For that, not using list seems like the right solution, as, with list, you must know how many elements the expression on the right of = will return...
And, in this situation, you don't know how many elements explode will return.
For instance, something like this might be OK :
$parts = explode('/', $url);
if (isset($parts[0])) {
$dir = $parts[0];
if (isset($parts[1])) {
$act = $parts[1];
}
}
Of course, up to you to deal with the situation in which $dir and/or $act are not set, later in your script.
Another solution would be to check how many elements explode will return (counting a number of / for instance) ; but you'll still have to deal with at least two cases.
to get rid of the notice:
list($dir, $act) = explode('/',$url);
but maybe a better solution would be:
$segments = explode ('/', $url);
$dir = array_shift ($segments);
$act = array_shift ($segments);
if there is no 2nd segment, $act would be null and you can also more than 2 segment this way
The correct way to suppress the E_NOTICE on list assignment as of PHP 5.4+ is the following:
#list($dir, $act) = explode('/', $url);
If $url contains no /, explode will return one element and $act will be NULL.
Instead of exploding the full URL, try $_SERVER['PATH_INFO'], assuming '/random' names the script.
The simple and ugly answer is to prefix the whole thing with a single '#' which suppresses error outputs. $act will be set to null in that case because under the hood, it's equivalent to:
$foo = explode('/',$url);
$dir = $foo[0];
$act = $foo[1]; // This is where the notice comes from

Categories