-3

summary: i need to get the youtube embed link in a paragraph

input : "Reduced crime in society\r\n\r\n\r\n

 

\r\n\r\n

https://www.youtube.com/embed/X6UW9MQ8aHs?control=0&rel=0&showinfo=0\" width=\"646\">

\r\n"

output excepted : https://www.youtube.com/embed/X6UW9MQ8aHs?control=0&rel=0&showinfo=0

1 Answers1

3

Maybe,

(?im)\b(?:https?:\/\/)?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)\/(?:(?:\??v=?i?=?\/?)|watch\?vi?=|watch\?.*?&v=|embed\/|)([A-Z0-9_-]{11})[^\\'"]*(?=\s|$|)

might work OK.


The key for modification of this expression is in the last few blocks, especially:

[^\\'"]*

which you'd want to see after that 11-char length ID of YouTube, what you'd wish to allow.


If you don't really want to capture the ID, then we'd simply turn the existing capturing group to a non-capturing group:

(?im)\b(?:https?:\/\/)?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)\/(?:(?:\??v=?i?=?\/?)|watch\?vi?=|watch\?.*?&v=|embed\/|)(?:[A-Z0-9_-]{11})[^\\'"]*(?=\s|$|)

If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


Test

$re = '/(?im)\b(?:https?:\/\/)?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)\/(?:(?:\??v=?i?=?\/?)|watch\?vi?=|watch\?.*?&v=|embed\/|)([A-Z0-9_-]{11})[^\\\\\'"]*(?=\s|$|)/m';
$str = 'Reduced crime in society</li>\\r\\n</ul>\\r\\n\\r\\n<p>&nbsp;</p>\\r\\n\\r\\n<p><iframe allowfullscreen=\\"\\" frameborder=\\"0\\" height=\\"297\\" src=\\"https://www.youtube.com/embed/X6UW9MQ8aHs?control=0&rel=0&showinfo=0\\" width=\\"646\\"></iframe></p>\\r\\n
Reduced crime in society</li>\\r\\n</ul>\\r\\n\\r\\n<p>&nbsp;</p>\\r\\n\\r\\n<p><iframe allowfullscreen=\\"\\" frameborder=\\"0\\" height=\\"297\\" src=\\\'https://www.youtube.com/embed/X6UW9MQ8aHs?control=0&rel=0&showinfo=0\\\' width=\\"646\\"></iframe></p>\\r\\n';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

var_dump($matches);

Output

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(68) "https://www.youtube.com/embed/X6UW9MQ8aHs?control=0&rel=0&showinfo=0"
    [1]=>
    string(11) "X6UW9MQ8aHs"
  }
  [1]=>
  array(2) {
    [0]=>
    string(68) "https://www.youtube.com/embed/X6UW9MQ8aHs?control=0&rel=0&showinfo=0"
    [1]=>
    string(11) "X6UW9MQ8aHs"
  }
}

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Source

PHP Regex to get youtube video ID?

Emma
  • 26,487
  • 10
  • 35
  • 65