views:

49

answers:

4
$link = http://site.com/view/page.php?id=50&reviews=show

How can we add &extra=video after id=50?

  • id is always numeric.
  • url can have many other variables after ?id=50
  • &extra=video should be added before the first & and after the 50 (value of id)

It will be used this way:

echo '<a href="' . $link . '">Get video</a>';

Thanks.

+1  A: 

Is ID always the first post parameter? If so, then you could jsut do some sort of string manipulation. Use strpos($link, "&") to find out the position where you want to insert. Then do a few substr() based on that position and then append them all together. Its kind of hacky I know, but it will definitely work.

$pos = strpos($link, "&");

$first = substr($link, 0, $pos);

$last = substr($link, $pos);

$extra = "&extra=video";

$newLink = $first . $extra . $last;

See this link for some of the string manipulation functions that I mentioned above: http://us3.php.net/strings

Siege898
using string functions for url parsing might produce unexpected results(specifically invalid urls) for different urls...
kgb
I agree. Thus why I asked if it was the first post parameter and said it was a hacky solution. I'm not proud of it but its early...
Siege898
+2  A: 

As Treffynnon says, the order seldomly matters. However, if you really need if for some reason, just use

  • parse_url to get the querystring
  • parse_str to create an array of parameter
  • array_splice to inject a parameter
  • http_build_query to rebuild a proper query string
Wrikken
+1  A: 

i would suggest to use functions specifically aimed at url parsing, not general string functions:

$link = 'http://site.com/view/?id=50&amp;reviews=show';
$query = array();
parse_str(parse_url($link, PHP_URL_QUERY), $query);
$query['extra'] = 'video';
$linkNew = http_build_url($link, array('query' => http_build_query($query)));
kgb
I really like `http_build_url`, but it should be mentioned the pecl HTTP extension is not included by default.
Wrikken
+1  A: 

This will do it for you

<?php 
    $linkArray = explode('&',$link);
    $linkArray[0] += '&extra=video';
    $link = implode('&',$linkArray);
?>
  1. Explode will split the link string at every &, so it doesn't care how many elements you have in the url.

  2. The first element, will be everything including the id=## before the first & sign. So we append whatever you want to appear after it.

  3. We put our array together again as a string, separating each element by an &.

Angelo R.