How do I get JavaScript Regular expressions to work properly in PHP preg_match?

I found a PHP script that converts YouTube links into videos and I also found a cool JavaScript version as well that does pretty much the same thing but for personal reason I want to use the PHP version but there is a problem the PHP version does a good

job in converting the YouTube links into videos but it doesn't convert all the YouTube links so I notice that the JavaScript version converts more different kinds of Youtube links then the PHP version so how can I convert the contents of the JavaScript expression

var regExp = /^.*(\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;

into a PHP form


//store the URL into a variable
$url = '';

//extract the ID

//the ID of the YouTube URL: x6qe_kVaBpg
$id = $matches[1];

//set a custom width and height
$width = '640';
$height = '360';

//echo the embed code. You can even wrap it in a class
echo '<div class="youtube-article"><iframe class="dt-youtube" width="' .$width. '" height="'.$height.'" src="//'.$id.'" frameborder="0" allowfullscreen></iframe></div>';


Keep in mind I don't want the JavaScript variable or any JavaScript code into the PHP script I just want the contents of the variable call reqExp only to work in the preg_match section in a PHP form.

1 answer

  • answered 2017-10-23 23:09 meza

    The simplest thing that comes in mind is to reduce the groups.

    var regExp = /^.*(\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;

    This basically has 2 regex groups, within braces. (). These get matched into the $matches part of the php script.

    The old PHP version only uses one group to get the ID out, so you need to modify the javascript regex to do the same OR modify the $id = $matches[1]; to $id = $matches[2];

    Since touching regex is always risky, I'd recommend the latter option. You might want to var_dump the $matches array to see exactly what's going on.