Search code examples
phpstringsubstrstrpos

How to find a string and select it to the end (unknown) in php


I need to find and select all the youtube links in a text with php in order to replace them with the proper embed code, but i don't seem to find the way.

1- Where the link start:
The link's start might change between https://www.youtube.com/watch?v=<video_id> and https://youtu.be/<video_id> and i think strpos() would do that job, the problem is....

2- Where it ends:
The link might have (or not) a query string attached what makes its length unknow, so the only way is select between https://www.youtube.co.... or https://youtu.b... and the next white space which would be the end of the link.

I need to replace the link with the proper youtube embed code.

Any idea how to select the link?


Solution

  • Try this regex

    (https:\/\/www\.youtube\.com\/.*?)(?:\s|$)|(https:\/\/youtu\.be\/.*?)(?:\s|$)
    

    example

    Usage:

    $re = '/(https:\/\/www\.youtube\.com\/.*?)(?:\s|$)|(https:\/\/youtu\.be\/.*?)(?:\s|$)/';
    $str = 'abc https://www.youtube.com/watch?v=Dx5qFachd3A def https://youtu.be/Dx5qFachd3A ghi';
    $embedStart = '<iframe width="560" height="315" src="';
    $embedEnd = '" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
    
    preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
    
    $str = preg_replace($re,$embedStart.'$0'.$embedEnd,$str);
    
    echo $str;
    

    you can use preg_replace to replace it with your embed code.