Extract number from variable - php

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
}

Related

Replace text if it matches another piece of text

So I have the following code to remove "page=" from a string. My problem now is that I want to query through "$qs_final" to check if it contains "price_range" and if so replace it with another piece of text. The price range variable is attached to "attr=" so I can't really use a $_GET request as other information is stored within it. The price_range variable also has the layout of "price_range_20".
<?php
$querystring = explode("&",$_SERVER['QUERY_STRING']);
$qs_nos = 0;
$qs_final = "";
while(isset($querystring[$qs_nos])) {
if(!ereg("page=",$querystring[$qs_nos])) {
$qs_final .= $querystring[$qs_nos]."&";
}
$qs_nos++;
}
if (strpos($qs_final,'price_range') !== false) {
print "true";
}
?>
str_replace().
$new_string = str_replace($what_to_replace, $what_to_replace_it_with, $old_string);
EDIT: To replace data, you need preg_replace(). In your case to remove "price_range" and all numbers and underscores directly after it, use this:
$new_string = preg_replace("/price_range[0-9_]+/", "", $old_string);

Getting id from url using regex

http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F1234567
http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F1234567%2Fsubtitle
http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F123456
http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F123456%2Fsubtitle
http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F1234567%2F
http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F123456%2F
The URL's always start with:
http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F
The ids are always numeric, however the number of digits can vary.
How to get the id (1234567 and 123456) from above sample URL's?
I've tried using the following pattern without luck (it doesn't return any matches):
/^http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F(\d)$/
I would recommend you to first parse this url and extract the url query string parameter and url decoding it:
function getParameterByName(url, name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
like this:
var url = 'http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F1234567';
var p = getParameterByName(url, 'url');
and then use some regex to parse p and extract the necessary information like /\d+/.
With proper URL parsing functions you can do this:
parse_str(parse_url($url, PHP_URL_QUERY), $params);
if (isset($params['url'])) {
parse_str(parse_url($params['url'], PHP_URL_QUERY), $params);
if (isset($params['movie'])) {
$movie = $params['movie'];
}
}
$urls = array(
'http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F1234567'
, 'http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F1234567%2Fsubtitle'
, 'http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F123456'
, 'http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F123456%2Fsubtitle'
, 'http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F1234567%2F'
, 'http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F123456%2F'
);
foreach ($urls as $url) {
if (preg_match('/%2Fmovie%2F(\d+)/', $url, $matches)) {
var_dump($matches[1]);
}
}
KISS. I was originally going to use parse_url(), but there is no way to parse a query string without regular expressions anyway.
There's a way without parsing too. Assuming $url = URL
http://codepad.org/t91DK9H2
$url = "http://example.com/movie.swf?url=http%3A%2F%2Fexample.com%2Fmovie%2F1234567%2Fsubtitle";
$reg = "/^([\w\d\.:]+).*movie%2F(\d+).*/";
$id = preg_replace($reg,"$2",$url);
It looks likes you need to escape some special characters.
try:
/^http://example.com/movie.swf\?url=http%3A%2F%2Fexample.com%2Fmovie%2F(\d+)$/

Function to remove GET variable with php

i have this URI.
http://localhost/index.php?properties&status=av&page=1
i am fetching basename of the URI using following code.
$basename = basename($_SERVER['REQUEST_URI']);
the above code gives me following string.
index.php?properties&status=av&page=1
i would want to remove the last variable from the string i.e &page=1. please note the value for page will not always be 1. keeping this in mind i would want to trim the variable this way.
Trim from the last position of the string till the first delimiter i.e &
Update :
I would like to remove &page=1 from the string, no matter in which position it is on.
how do i do this?
Instead of hacking around with regular expression you should parse the string as an url (what it is)
$string = 'index.php?properties&status=av&page=1';
$parts = parse_url($string);
$queryParams = array();
parse_str($parts['query'], $queryParams);
Now just remove the parameter
unset($queryParams['page']);
and rebuild the url
$queryString = http_build_query($queryParams);
$url = $parts['path'] . '?' . $queryString;
There are many roads that lead to Rome. I'd do it with a RegEx:
$myString = 'index.php?properties&status=av&page=1';
$myNewString = preg_replace("/\&[a-z0-9]+=[0-9]+$/i","",$myString);
if you only want the &page=1-type parameters, the last line would be
$myNewString = preg_replace("/\&page=[0-9]+/i","",$myString);
if you also want to get rid of the possibility that page is the only or first parameter:
$myNewString = preg_replace("/[\&]*page=[0-9]+/i","",$myString);
Thank you guys but i think i have found the better solution, #KingCrunch had suggested a solution i extended and converted it into function. the below function can possibly remove or unset any URI variable without any regex hacks being used. i am posting it as it might help someone.
function unset_uri_var($variable, $uri) {
$parseUri = parse_url($uri);
$arrayUri = array();
parse_str($parseUri['query'], $arrayUri);
unset($arrayUri[$variable]);
$newUri = http_build_query($arrayUri);
$newUri = $parseUri['path'].'?'.$newUri;
return $newUri;
}
now consider the following uri
index.php?properties&status=av&page=1
//To remove properties variable
$url = unset_uri_var('properties', basename($_SERVER['REQUEST_URI']));
//Outputs index.php?page=1&status=av
//To remove page variable
$url = unset_uri_var('page', basename($_SERVER['REQUEST_URI']));
//Outputs index.php?properties=&status=av
hope this helps someone. and thank you #KingKrunch for your solution :)
$pos = strrpos($_SERVER['REQUEST_URI'], '&');
$url = substr($_SERVER['REQUEST_URI'], 0, $pos - 1);
Documentation for strrpos.
Regex that works on every possible situation: /(&|(?<=\?))page=.*?(?=&|$)/. Here's example code:
$regex = '/(&|(?<=\?))page=.*?(?=&|$)/';
$urls = array(
'index.php?properties&status=av&page=1',
'index.php?properties&page=1&status=av',
'index.php?page=1',
);
foreach($urls as $url) {
echo preg_replace($regex, '', $url), "\n";
}
Output:
index.php?properties&status=av
index.php?properties&status=av
index.php?
Regex explanation:
(&|(?<=\?)) -- either match a & or a ?, but if it's a ?, don't put it in the match and just ignore it (you don't want urls like index.php&status=av)
page=.*? -- matches page=[...]
(?=&|$) -- look for a & or the end of the string ($), but don't include them for the replacement (this group helps the previous one find out exactly where to stop matching)
You could use a RegEx (as Chris suggests) but it's not the most efficient solution (lots of overhead using that engine... it's easy to do with some string parsing:
<?php
//$url="http://localhost/index.php?properties&status=av&page=1";
$base=basename($_SERVER['REQUEST_URI']);
echo "Basename yields: $base<br />";
//Find the last ampersand
$lastAmp=strrpos($base,"&");
//Filter, catch no ampersands found
$removeLast=($lastAmp===false?$base:substr($base,0,$lastAmp));
echo "Without Last Parameter: $removeLast<br />";
?>
The trick is, can you guarantee that $page will be stuck on the end? If it is - great, if it isn't... what you asked for may not always solve the problem.

retrieving a parameter from a string

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
}

PHP update url in variable

$link = http://site.com/view/page.php?id=50&reviews=show
How can we add &extra=video after id=50?
id is always numeric.
url can have many other variables after ?id=50
&extra=video should be added before the first & and after the 50 (value of id)
It will be used this way:
echo 'Get video';
Thanks.
As Treffynnon says, the order seldomly matters. However, if you really need if for some reason, just use
parse_url to get the querystring
parse_str to create an array of parameter
array_splice to inject a parameter
http_build_query to rebuild a proper query string
This will do it for you
<?php
$linkArray = explode('&',$link);
$linkArray[0] += '&extra=video';
$link = implode('&',$linkArray);
?>
Explode will split the link string at every &, so it doesn't care how many elements you have in the url.
The first element, will be everything including the id=## before the first & sign. So we append whatever you want to appear after it.
We put our array together again as a string, separating each element by an &.
Is ID always the first post parameter? If so, then you could jsut do some sort of string manipulation. Use strpos($link, "&") to find out the position where you want to insert. Then do a few substr() based on that position and then append them all together. Its kind of hacky I know, but it will definitely work.
$pos = strpos($link, "&");
$first = substr($link, 0, $pos);
$last = substr($link, $pos);
$extra = "&extra=video";
$newLink = $first . $extra . $last;
See this link for some of the string manipulation functions that I mentioned above: http://us3.php.net/strings
i would suggest to use functions specifically aimed at url parsing, not general string functions:
$link = 'http://site.com/view/?id=50&reviews=show';
$query = array();
parse_str(parse_url($link, PHP_URL_QUERY), $query);
$query['extra'] = 'video';
$linkNew = http_build_url($link, array('query' => http_build_query($query)));

Categories