privateFunction
privateFunction

Reputation: 51

Regex - BBCode for Youtube tag

<?php

function convertYoutube($string) {
    return preg_replace(
        "/\s*[a-zA-Z\/\/:\.]*youtu(be.com\/watch\?v=|.be\/)([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i",
        "<iframe width=\"420\" height=\"315\" src=\"//www.youtube.com/embed/$2\" allowfullscreen></iframe>",
        $string
    );
}

$text = "Youtube long url: https://www.youtube.com/watch?v=waIkasvAVGo\n\nYoutube short url: http://youtu.be/waIkasvAVGo";

echo convertYoutube($text);

I found this code on this site: http://syframework.alwaysdata.net/convert-youtube-url-to-iframe.

The script works just fine. But want this just to work within a BBcode.

For example: [YouTube]<url>[/YouTube].

Does anyone have suggestions to how this can be resolved?

Upvotes: 1

Views: 488

Answers (1)

NetVicious
NetVicious

Reputation: 4037

Try this:

<?php

    function convertYoutube($string) {
        return preg_replace(
            "/\[youtube\]\s*[a-zA-Z\/\/:\.]*youtu(be.com\/watch\?v=|.be\/)([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)\[\/youtube\]/i",
            "<iframe width='420' height='315' src='//www.youtube.com/embed/$2' allowfullscreen></iframe>",
            $string
        );
    }

    $text = "Youtube long url: [youtube]https://www.youtube.com/watch?v=waIkasvAVGo[/youtube]\n\nYoutube short url: [youtube]http://youtu.be/waIkasvAVGo[/youtube]";

    echo convertYoutube($text);
?>

Upvotes: 1

Related Questions