Regex PHP - automatic detection of YouTube, images and "regular" links

I want to make sure that in my chat application links to sites can be clicked and links to YouTube, and images are automatically inserted.

I made this code in Java for my WebIRC client, but now I'm trying to do it in PHP and JavaScript.

I am not familiar with PHP yet, so I don’t know how much to use regex. I wonder if any soul can help me with this ...

For the YouTube-thingy, I tried this without success:

if (preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $message, $m)) { $video_id = $m[1]; $message = preg_replace("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#","<iframe class='embedded-video' src='http://www.youtube.com/embed/" . $video_id . "' allowfullscreen></iframe>",$message); } 
+4
source share
3 answers

Here is the solution I came up with:

 $str = 'This is an image: google.ca/images/srpr/logo3w.png YouTube: http://www.youtube.com/watch?v=V2b8ilapFrI&feature=related Stackoverflow: http://stackoverflow.com/'; $str = preg_replace_callback('#(?:https?://\S+)|(?:www.\S+)|(?:\S+\.\S+)#', function($arr) { if(strpos($arr[0], 'http://') !== 0) { $arr[0] = 'http://' . $arr[0]; } $url = parse_url($arr[0]); // images if(preg_match('#\.(png|jpg|gif)$#', $url['path'])) { return '<img src="'. $arr[0] . '" />'; } // youtube if(in_array($url['host'], array('www.youtube.com', 'youtube.com')) && $url['path'] == '/watch' && isset($url['query'])) { parse_str($url['query'], $query); return sprintf('<iframe class="embedded-video" src="http://www.youtube.com/embed/%s" allowfullscreen></iframe>', $query['v']); } //links return sprintf('<a href="%1$s">%1$s</a>', $arr[0]); }, $str); 

Let me know if you need me to explain something to you.

+12
source

I had some problems with preg_replace_callback when the text included three dots ... The above code recognized the three points as a URL that is not true.

Here is my fix and seems to be working at the moment $str = preg_replace_callback('#(?:https?://\S+)|(?:www.\S+)|(?:jpe?g|png|gif)#', function($arr)

Will this correction not be done in other cases?

+2
source

Tim Cooper code does not work with https link. Example: https://www.facebook.com/ It will return http: // https: //www.facebook.com/

Replace

 if(strpos($arr[0], 'http://') !== 0) 

by

 if(strpos($arr[0], 'http') !== 0) 
0
source

Source: https://habr.com/ru/post/1379861/


All Articles