Extract a number from a variable

I have this line:

$guid = 'http://www.test.com/?p=34';

How can I extract the value of get var p(34) from a string and have $guid2 = '34'?

+5
source share
5 answers
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $vars);
$guid2 = $vars['p'];
+16
source

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 remove nothing but a number from the URL string. However, this will not cause other URLs to appear in the URL. The solution proposed by konforce is the most reliable approach if you want to extract the value of the p parameter for the query string.

+3
source

A preg_replace(), , , , . konforce - URL-, URL-, , .

$guid = 'http://www.test.com/?p=34';
$guid2 = preg_replace("/^.*[&?;]p=(\d+).*$/", "$1", $guid);

Note that if a variable cannot be specified in the URLs p=<number>, then you will need to use match instead, since preg_replace () will not match and will return the entire string.

$guid = 'http://www.test.com/?p=34';
$matches = array();
if (preg_match("/^.*[&?;]p=(\d+).*$/", $guid, $matches)) {
    $guid2 = $matches[1];
} else {
    $guid2 = false;
}
+1
source

This is WordPress. On one page of messages, you can use the get_the_ID () function (built-in WP, used only in a loop).

0
source
$guid2 = $_GET['p']

For greater security:

if(isset($_GET['p']) && $_GET['p'] != ''){
    $guid2 = $_GET['p'];
}
else{
    $guid2 = '1'; //Home page number
}
0
source

All Articles