sharataka
sharataka

Reputation: 5132

How to parse defined strings in php?

In the below URL, I am trying to parse out the string everything that appears after "scid=" and "pid=" into 2 different variables. The two numbers associated with pid and scid don't have a fixed number of digits each time (they change). I'm approaching the problem in the following way: find location of "pid=" and parse out the string from after this location until the next "&". How do I do this?

http://oldnavy.gap.com/browse/product.do?cid=78425&vid=1&pid=113855&scid=113855012

Upvotes: 0

Views: 100

Answers (2)

TecBrat
TecBrat

Reputation: 3729

If that URL was used to access the current page, then see the earlier comment about $_GET.

<?php
$pid=$_GET['pid'];
$scid=$_GET['scid'];
?>

If you otherwise access that as a string, here's a bit of code I have used to pull out pieces of text before:

<?php
//assumes that the URL is the value of $string.
list($temp,$pid)=split('pid=',$string);
list($pid,$temp)=split('&',$pid);

list($temp,$scid)=split('scid=',$string);
list($scid,$temp)=split('&',$scid); //allows for other name / value pairs to follow.

?>

Upvotes: 0

deceze
deceze

Reputation: 522145

parse_str(parse_url($url, PHP_URL_QUERY), $values);

echo $values['scid'];
echo $values['pid'];

See http://php.net/parse_str and http://php.net/parse_url.

Upvotes: 6

Related Questions