Andrew Gage
Andrew Gage

Reputation: 17

Using preg_replace to alter youtube links

I want to change the standard youtube video links (like: https://www.youtube.com/watch?v=zVzhpkFBFP8) stored in my database to embeded urls (like: https://www.youtube.com/embed/zVzhpkFBFP8) using preg_replace. This is my code so far:

<?php
    $Link = getuser($my_id, 'YoutubeLink'); 
    $LinkNew = preg_replace("/watch?v=*/","embed*/","$Link");
    echo "$LinkNew" ?>

But it isn't working. I'm probably doing something stupid but I'm new to php so any help is appreciated.

Upvotes: 1

Views: 179

Answers (2)

chris85
chris85

Reputation: 23892

Your regex as is doesn't work because the ? is a special character in regex so you need to escape it. The question mark makes the preceding character optional. To escape just add a backslash before it \?.

The * also is being used somewhat incorrectly. The asterisk is a quantifier so you are saying zero or more equal signs. If you wanted everything after the equals sign you'd do .*. That would get every other character because . is any character and paired with the * is everything. You don't actually want to do that either because you aren't grouping that and the replace would just delete it. If you were to group that you could use that value later in the replace using $1. Here's a write up on that http://www.regular-expressions.info/brackets.html.

<?php
    $Link = getuser($my_id, 'YoutubeLink'); 
    $LinkNew = preg_replace("/watch\?v=/","embed/", $Link);
    echo "$LinkNew"; ?>

As @V13Axel has pointed out though this can be done just as easily using str_replace.

Upvotes: 0

V13Axel
V13Axel

Reputation: 838

No need to use preg_replace for something like that in which there is no pattern. As watch?v= is always the same, instead use str_replace('watch?v=', 'embed/', $Link);

Upvotes: 2

Related Questions