Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract number from variable

Tags:

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'?

like image 912
webmasters Avatar asked Nov 21 '10 12:11

webmasters


People also ask

How do you extract a number from a string in Excel?

Extract Numbers from String in Excel (using VBA) Since we have done all the heavy lifting in the code itself, all you need to do is use the formula =GetNumeric(A2). This will instantly give you only the numeric part of the string.

How do you turn a variable into a number?

One way is to use the number function with the compute command. To do this, you need to create a new variable using the compute command. To use the number function, you need to enclose the name of the string variable and a format for the new numeric variable. compute score1 = number(score, F2).

How do I extract numbers from a string in Python?

To find numbers from a given string in Python we can easily apply the isdigit() method. In Python the isdigit() method returns True if all the digit characters contain in the input string and this function extracts the digits from the string. If no character is a digit in the given string then it will return False.


3 Answers

$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $vars);
$guid2 = $vars['p'];
like image 74
Matthew Avatar answered Oct 06 '22 04:10

Matthew


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.

like image 38
Gordon Avatar answered Oct 06 '22 03:10

Gordon


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;
}
like image 33
Orbling Avatar answered Oct 06 '22 04:10

Orbling