Php preg_replace更改图像宽度

I have some images in my database

http://***.com/2013/12/reign-death-midseason-finale-featured.jpg?w=500
http://***.com/reign-death-midseason-finale-featured.png?w=120
http://***.com/2013/12/finale-featured.jpg?w=50
http://***.com/2013/finale-featured.jpg?w=50&h=50
http://***.com/2013/12/reign-death-midseason-finale-featured.jpg

I want to change the images with w= to same width and ?w=50&h=50 also. all with W should come as w=600 and w=600&h=600. This is what I was trying str_replace but there is a problem with this that w= always change and in some cases there is height also and it also need to be changed, i have search net and found that it can be done with preg_replace don't know how.

EDIT

Answer needed is if(hight is null) result is case 1 w=600 and if h is not null case 2 w=600&h=600 please help

Sorry it took me a while, I was kinda busy

try the following

$pattern = '~(?<=\W(w|h)\=)(\d+?)(?=\D|$)~';
$replace = '600';
$subject = 'http://localhost/2013/finale-featured.jpg?w=50&h=50';
echo preg_replace($pattern,$replace,$subject);

try this with many variations of your URIs

PS: this kind of advanced string finding/replacing is the domain of regular expressions. If you find you need to do a lot of this, consider starting to learn about them, it's a whole language in itself. I used some assertions (lookahead (?<=) and lookbehind (?=)) for this particular solution

If you want to avoid using a regular expression you can parse the URL and query string into arrays, which would make evaluating the query string values much easier.

$url = 'http://***.com/2013/finale-featured.jpg?w=50&h=50';
$urlArray = parse_url($url);
parse_str($urlArray['query'], $queryStringArray);
if ( !isset($queryStringArray['h']) || $queryStringArray['h'] === null ) {

} else if ( ... ) {

} else if ( ... ) {

}