开发者

Extract number from variable

I have this stri开发者_高级运维ng:

$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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜