PHP update url in variable
$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 the50
(value ofid
)
It will be used this way:
echo '<a href="' . $link . '">Get video</a>';
Thanks.
As Treffynnon says, the order seldomly matters. However, if you really need if for some reason, just use
parse_url
to get the querystringparse_str
to create an array of parameterarray_splice
to inject a parameterhttp_build_query
to rebuild a proper query string
This will do it for you
<?php
$linkArray = explode('&',$link);
$linkArray[0] += '&extra=video';
$link = implode('&',$linkArray);
?>
Explode will split the link string at every &, so it doesn't care how many elements you have in the url.
The first element, will be everything including the id=## before the first & sign. So we append whatever you want to appear after it.
We put our array together again as a string, separating each element by an &.
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
i would suggest to use functions specifically aimed at url parsing, not general string functions:
$link = 'http://site.com/view/?id=50&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)));
精彩评论