Regular expression to get Youtube link in text

0

I have text in wordpress and this text has a link to youtube:

  

Health "every Monday, at 9:15 am, with a repeat of the   Fridays, from 1 pm

During the   attraction, the presenter usually receives health professionals to   feeding, medication, posture and quality of life   viewers.      

link

     

Brief history of the presenter: Gisela Savioli was the nutritionist   responsible for feeding the

I have created this express, but it is not working, it is still coming null, can anyone help me?

public function getUrlFromContent($content){
    $video_url=null;
    $pattern = '/(youtu|y2u)(be)?\.(com|be)(\.br)?\/(watch\?v=)?[^"\&\?\/ ]{11}/i';
    preg_match($pattern, $content, $result_youtube);
    if (isset($result_youtube[0])) {  
        $video_url = "http://" . $result_youtube[0];
    }
    return $video_url;
}
    
asked by anonymous 08.10.2015 / 14:42

2 answers

1

I think this can help, basically I changed the $ pattern.

<?php

$content = 'Saúde" todas as segundas-feiras, às 9h15, com reprise às sextas-feiras, a partir das 13 horas.

Durante a exibição da atração, a apresentadora costuma receber profissionais da saúde para dar dicas de alimentação, medicação, postura e qualidade de vida aos telespectadores.
https://www.youtube.com/watch?v=tNR3lGyiLQA

Breve histórico da apresentadora: Gisela Savioli foi a nutricionista responsável pela alimentação dos';



function getUrlFromContent($content){
    $video_url=null;
    $pattern = '~http(s){0,1}://(www.){0,1}(youtube.com/watch\?v=|y2u.be/|youtu.be/)[a-zA-Z0-9]{1,}~';
    // $pattern = '/(youtu|y2u)(be)?\.(com|be)(\.br)?\/(watch\?v=)?[^"\&\?\/ ]{11}/i';
    preg_match($pattern, $content, $result_youtube);
    if (isset($result_youtube[0])) {  
        $video_url = $result_youtube[0];
    }
    return $video_url;
}


echo getUrlFromContent($content);

NOTE: I have also edited to accept Youtube shortcuts .

I hope I have helped!

    
08.10.2015 / 15:19
0

As I do not know if the link will always come with a line break at the end, I have defined that the size of the string that defines the video will be between 8 and 11 characters.

 ((https?:\/\/)?www\.youtube\.com\/watch\?\w=.{8,11})

This is optional between:

If you have a line break or space after the link.

((https?:\/\/)?www\.youtube\.com\/watch\?\w=[^ \n]+)
    
08.10.2015 / 15:21