0

Unable to figure out why the following code doesn't work.

It takes text file content (string), replaces the youtube url (from the string) then embed it to other string, but I am getting no response.

// regex
$yt_pre = "/https?:\/\/(?:www)?\.youtu(?:\.be|be\.com)\/watch(?:\?(.*?)&|\?)v=([a-zA-Z0-9_\-]+)(\S*)/i";

// find
preg_match($yt_pre, $text, $yt_find);
$yt_loc = $yt_find[1];

// embed
$yt_rep = "<div class='youtube'><iframe src='https://www.youtube.com/embed/" . $yt_loc . "' frameborder='0' allowfullscreen class='youtube_iframe'></iframe></div>";

// replace
preg_replace($yt_pre, $yt_rep, $text);
justnajm
  • 4,422
  • 6
  • 36
  • 56
Vimmy
  • 71
  • 1
  • 7
  • 1
    What do you mean with "but I get no response"? What is the content of `$text`? What do you get? What do you expect? – Toto Jun 17 '19 at 17:54
  • @Toto The $text file has text with some html tags and links. It's used to fill a page by get_file_content etc. I am trying to convert the youtube links in the text to embed code. When I check for warnings or source .. I get no change at all from the code above. No alerts, not warnings, nothing. – Vimmy Jun 17 '19 at 18:12
  • Show us an extract of the input file and expected result. – Toto Jun 18 '19 at 07:41
  • added more clarity code – justnajm Jun 19 '19 at 06:33

1 Answers1

0

My guess is that this expression might work for youtube links, which I have assumed that we'd have an ID with this pattern (([A-Za-z0-9_-]{11})):

https?:\/\/(?:www\.)?youtu(?:be)?(?:\.com|\.be)\/(?:watch\?v=|embed\/watch\?feature=player_embedded&v=)?([A-Za-z0-9_-]{11})(.+)?

Demo

$re = '/https?:\/\/(?:www\.)?youtu(?:be)?(?:\.com|\.be)\/(?:watch\?v=|embed\/watch\?feature=player_embedded&v=)?([A-Za-z0-9_-]{11})(.+)?/m';
$str = 'http://www.youtube.com/watch?v=iwGFalTRHDA
http://www.youtube.com/watch?v=iwGFalTRHDA&feature=related
http://youtu.be/iwGFalTRHDA
http://youtu.be/n17B_uFF4cA
http://www.youtube.com/embed/watch?feature=player_embedded&v=r5nB9u4jjy4
http://www.youtube.com/watch?v=t-ZRX8984sc
http://youtu.be/t-ZRX8984sc';

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

var_dump($matches);

Ref

Emma
  • 27,428
  • 11
  • 44
  • 69