Search code examples
phppreg-match

Combine two preg match to get viemo id and youtube id from url


I have a client that may embed vimeo video or youtube video. so i want to write a regex that get the id from url .

here's what i did :

 $y = '%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i';
 $v = '(https?:\/\/)?(www\.)?(player\.)?vimeo\.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*';
 preg_match(($y) | ($v), $markup, $match);
 $markup = preg_replace('#\<iframe(.*?)\ssrc\=\"(.*?)\"(.*?)\>#i', '<iframe$1 src="$2&loop=1&amp;playlist='.$match[1].'"$3>', $markup);

but it gives me an error :

Warning: preg_match(): Unknown modifier '|' in

any idea ? Thanks in advance


Solution

  • You can't OR regex patterns like you do in preg_match($rx1 || $rx2, $text), you should use a single regex with | separating alternatives. However, it might become too tricky here, as you need to capture a specific group. You might use either a branch reset group ((?|...|...) where alternatives retain grouping IDs) or \K operator (that omits the text matched so far):

    '~(?|(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})|vimeo\.com/(?:[a-z]+/)*([0-9]{6,11}))~'
    

    See the regex demo. Or with \K:

    '~(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)\K[^"&?/ ]{11}|vimeo\.com/(?:[a-z]+/)*\K[0-9]{6,11}~'
    

    See another regex demo

    PHP code:

    $rx = '~(?|(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})|vimeo\.com/(?:[a-z]+/)*([0-9]{6,11}))~';
    $s = 'https://vimeo.com/341989332 or https://www.youtube.com/watch?v=eUMbH6X_Adc';
    if (preg_match_all($rx, $s, $m)) {
        print_r($m[1]);
    }
    // => Array ( [0] => 341989332    [1] => eUMbH6X_Adc )