-1

i want to get a youtube links inside string example

"hi how are you check it https://www.youtube.com/watch?v=r_p8ZXIRFJI";

and then i get the links

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

after i get the link, i want to delete that link from string

For all youtube URLs

Tsitna FZ
  • 11
  • 4

2 Answers2

0

Here we are using regular expression to extract youtube links from string.

Regex: (?:https?:\/\/)(?:www\.)?(?:youtube|youtu)\.(?:be|com)\/[^\s]+

Try Regex demo here

Note: Youtube link can be this format also https://youtu.be/_3tVL-ZAc4k

Example string : hi how are you check it https://www.youtube.com/watch?v=r_p8ZXIRFJI youtube link can be of this type https://youtu.be/_3tVL-ZAc4k

Try this code snippet here

<?php

$string="hi how are you check it https://www.youtube.com/watch?v=r_p8ZXIRFJI youtube link can be of this type https://youtu.be/_3tVL-ZAc4k";
preg_match_all("/(?:https?:\/\/)(?:www\.)?(?:youtube|youtu)\.(?:be|com)\/[^\s]+/", $string,$matches);
print_r($matches);

Output:

Array
(
    [0] => Array
        (
            [0] => https://www.youtube.com/watch?v=r_p8ZXIRFJI
            [1] => https://youtu.be/_3tVL-ZAc4k
        )

)
Community
  • 1
  • 1
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
0

Using @aampudia answer, from Extract URL's from a string using PHP you can get URL's and parse it like,

<?php
    $pattern='#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#';
    $str="hi how are you check it https://www.youtube.com/watch?v=r_p8ZXIRFJI";
    preg_match_all($pattern, $str, $match);
    // if there are multiple urls then use loop here
    print_r($match[0]);
    echo '<br/>';
    // otherwise just use 
    echo isset($match[0][0]) ? $match[0][0] : 'No url found';
    // and to replace string use
    echo '<br/>';
    echo strpos($match[0][0],'.youtube.') ? str_replace($match[0][0],'',$str) : 'No youtube url'; // let $match[0][0] is defined and not null
?>

PhpFiddle

Community
  • 1
  • 1
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106