2

I need to extract a variable's value from a string, which happens to be a URL. The string/url is loaded as part of a separate php query, not the url in the browser.

The url's will look like:

index.php?option=com_content&view=article&catid=334:golfeq&id=2773:xcelsiors&Itemid=44

How can I always find & capture the value of the id which in this example is 2773?

I read several examples already, but what I've tried captures the id value of the current page which is being viewed in the browser, and not the URL string.

Thanks

1
  • The value of id is not "2773" but "2773:xcelsiors". Commented Dec 4, 2011 at 10:28

3 Answers 3

6

You are looking for a combination or parse_url (which will isolate the query string for you) and parse_str (which will parse the variables and put them into an array).

For example:

$url = 'index.php?option=com_content&view=article&catid=334:golfeq&id=2773:xcelsiors&Itemid=44';

// This parses the url for the query string, and parses the vars from that
// into the array $vars (which is created on the spot).
parse_str(parse_url($url, PHP_URL_QUERY), $vars);

print_r($vars); // see what's in there

// Parse the value "2773:xcelsiors" to isolate the number
$id = reset(explode(':', $vars['id']));

// This will also work:
$id = intval($vars['id']);

echo "The id is $id\n";

See it in action.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the response. I think I'm seeing the symptoms of why this is not working for me. When i perform the print_r($vars), instead of getting for example [catid] => 334:golfeq it's showing [amp;catid] => 334 So I think there's some problem processing the "&". Any idea how I can address that?
1

You can use parse_str

1 Comment

The string is not the site's URL, hence the values won't be in the $_GET array.
0

You can use parse_url to parse URLs!

But you can use, to extract directly the numbers of ID variable:

$url = 'index.php?option=com_content&view=article&catid=334:golfeq&id=2773:xcelsiors&Itemid=44';
$id = preg_replace("/^.*[&?]id=([0-9]+).*$/",'$1',$url);
echo $id;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.