<?php
if (isset($_REQUEST['msg'])) {
    $html = '<!DOCTYPE html>
<html><head>
    <title>LinkGen - Output</title>
</head><body>
    <p><pre>
';
    $regex = [
        // Regex #1: Youtube
        '/(\s|^)(' .                                                 // Whitespace davor
        'https?:\/\/(((www\.)?youtube(-nocookie)?\.com\/watch\?v=)|(youtu\.be\/))' . // Domain, Pfad
        '([a-zA-Z0-9_-]{8,16}' .                                     // Video-ID
        '([&\?]((t=[0-9hms]{2,9})|(list=[a-zA-Z0-9_-]{16,48})))?)' . // Zeit oder Liste
        '([&\?][a-zA-Z0-9_=-]+)*' .                                  // Anhängsel
        ')(\s|$)/'                                                   // Whitespace danach
        ,
        // Regex #2: URLs
        '/(\s|^)(' .                           // Whitespace davor
        '((https?|ftp):\/\/)' .                // Protokoll
        '([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+' . // Subdomains, Domain
        '([a-zA-Z]{2,16}\.?)' .                // TLD
        '(\/[\x23-\x7E!äöüÄÖÜß]*)*' .          // Anhängsel (Pfad, Parameter, Anker, ...)
        ')(\s|$)/'                             // Whitespace danach
    ];
    $replace = [
        // Replace #1: Youtube
        '$1<iframe width="560" height="315" ' .
        'src="//www.youtube-nocookie.com/embed/$7" ' .
        'frameborder="0" allowfullscreen></iframe>$14'
        ,
        // Replace #2: URLs
        '$1<a href="$2">$2</a>$9'
    ];
    $html .= preg_replace( $regex, $replace, $_REQUEST['msg']);
    $html .= '
    </pre></p>
</body></html>
';
} else {
    $html = "<!DOCTYPE html>
<html><head>
    <title>LinkGen - Input</title>
</head><body>
    <form>
        <textarea name=msg id=msg autofocus=yes cols=80 rows=12></textarea><br>
        <button type=submit>Submit</button>
    </form>
</body></html>
";
}

echo $html;
?>
