Hai Truong IT
Hai Truong IT

Reputation: 4187

Error using preg_relace to change url youtube?

I have a sample code:

<?php
$url = 'http://www.youtube.com/watch?v=KTRPVo0d90w';
$pattern = '/http:\/\/www\.youtube\.com\/watch\?(.*?)v=([a-zA-Z0-9_\-]+)(\S*)/i';
$replace = $pattern.'&w=550';
$string = preg_replace($pattern, $replace, $url);
?>

How to result is http://www.youtube.com/watch?v=KTRPVo0d90w&w=550

Upvotes: 0

Views: 80

Answers (4)

Funk Forty Niner
Funk Forty Niner

Reputation: 74217

Don't get me wrong, I'm not looking to gain any points here, but just thought I would add to this question and include a few options. I love toying with ideas like this every once in a while.

Using jh314's idea to concatenate the strings, thought that this could be used for future use, to actually replace a string inside the video's YouTube number, should the occasion ever present itself.

Such as $number for instance.

<?php

$url = 'http://www.youtube.com/watch?v=';
$number = 'KTRPVo0d90w';
$string = $url.$number.'&w=550';

// Output to screen
echo $string;

echo "<br>";

// Link to video
echo "<a href=\"$string\">Click for the video</a>";

?>

The same could easily be done for the video's width.

Upvotes: 0

TURTLE
TURTLE

Reputation: 3847

Like below?

$url = 'http://www.youtube.com/watch?v=KTRPVo0d90w';
$bit = '&w=550';
echo "${url}${bit}";

Upvotes: 0

Ghilas BELHADJ
Ghilas BELHADJ

Reputation: 14096

Use preg_match instead:

<?php
    $url = 'http://www.youtube.com/watch?v=KTRPVo0d90w&s=222';
    $pattern = '/v=[^&]+/i';
    preg_match($pattern, $url, $match);
    echo 'http://www.youtube.com/watch?'.$match[0].'&w=550';
?>

Upvotes: 0

jh314
jh314

Reputation: 27792

You can just append using the . operator:

<?php
$url = 'http://www.youtube.com/watch?v=KTRPVo0d90w';
$string = $url.'&w=550';
?>

Upvotes: 2

Related Questions