Regular expression to grab Youtube link in text

Asked

Viewed 224 times

0

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

Health" every Monday at 9:15 with reruns at Fridays, from 1 pm.

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

https://www.youtube.com/watch?v=tNR3lGyiLQA

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

created this express, but it’s not working, it’s still coming null, someone can 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;
}

2 answers

1

I think this might 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 edited to accept too short links from Youtube.

I hope I’ve helped!

0

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

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

This way is optional between :

If you have line break or space after the link.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.