Zaffar Saffee
Zaffar Saffee

Reputation: 6305

Getting a part from a string

I am trying to collect all CatIDs from a site...the URL structure is...

http://www.abc.com/family/index.jsp?categoryId=12436777

I am interested in it categoryId which is in this case is 12436777

My question is

Which is best, Regex or string explode??

if regex, please help me, I am very bad on it..

Also, I have to consider that URLs like

http://www.abc.com/product/index.jsp?productId=12282785

I tried

$array = explode("http://www.abc.com/family/index.jsp?categoryId=", $loc); 

foreach ($array as $part) {
        $zee[] = $part[1];
}

but it gives me nothing ..

thanks for help..

Upvotes: 1

Views: 127

Answers (7)

Tim Fountain
Tim Fountain

Reputation: 33148

You can use parse_url to reliably give you the query string:

$parts = parse_url('http://www.abc.com/family/index.jsp?categoryId=12436777');

and then parse_str to parse out the variables:

parse_str($parts['query'], $result);
echo $result['categoryId']; // outputs 12436777

Upvotes: 6

Sam
Sam

Reputation: 2970

If you're sure that what , is the only number, just do this

$st = "http://www.abc.com/family/index.jsp?categoryId=12436777";

echo preg_filter('/[^0-9]/','',$st);

Upvotes: 1

Stepo
Stepo

Reputation: 1056

Code:

$url = "http://www.abc.com/family/index.jsp?categoryId=12436777";

$parts = Explode('=', $url);

$id = $parts[count($parts) - 1];

Demonstration:

Upvotes: 1

fedorqui
fedorqui

Reputation: 289715

explode' s first param is the separator item. If you want to use it, try with something like:

$loc = "http://www.abc.com/family/index.jsp?categoryId=12436777";
$res=explode("=", $loc);

and the id will be in $res[1]

Upvotes: 1

Martin
Martin

Reputation: 6687

How about:

$url_parts = parse_url('http://www.abc.com/family/index.jsp?categoryId=12436777');

if (isset($url_parts['query'])) {
  $query_parts = explode('&', $url_parts['query']); 

  $keys = array(); 
  foreach ($query_parts as $part) { 
      $item = explode('=', $part); 
      $keys[$item[0]] = $item[1]; 
  } 

  $category_id = isset($keys['categoryId']) ? $keys['categoryId'] : 0;
}

Upvotes: 2

michi
michi

Reputation: 6625

try...

  list(,$id) = explode('=','http://www.abc.com/product/index.jsp?productId=12282785');

this will work if there's 1 = in the string

Upvotes: 1

Oscar Mederos
Oscar Mederos

Reputation: 29823

You can use the following regex:

http://.+?Id=(\d+)

The 1st group will contain the ID you're looking for.

Upvotes: 2

Related Questions