ClarkeRubber

String to YouTube Embedding and Hyperlinks (HTML SAFE!!!)

May 21st, 2012
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.02 KB | None | 0 0
  1. Given a string $body, the functino string_to_links_and_embedded() will return a string where all youtube video links are converted to embedded objects and links such as 'google.com' are converted to click-able hyperlinks. The rest of the $body is htmlspecialchars() so it is safe for displaying on a website.
  2.  
  3. <?php
  4. function link_array_sort($a, $b){
  5.     if($a[1] == $b[1]){
  6.         return 0;
  7.     }
  8.     return ($a[1] < $b[1]) ? -1 : 1;
  9. }
  10.  
  11. function string_to_links_and_embedded($body){
  12.     $pattern[0] = '#(http:\/\/)?(www\.)?youtube\.com/watch\?((&?v=([a-zA-Z0-9_-]+))|(&?[a-zA-Z0-9_-]+=[a-zA-Z0-9_-]+))*#';
  13.     $pattern[1] = '#((?!.*com\/embed\/.*)(?!.*com\/watch?.*)(http:\/\/)?(www\.)?[a-zA-Z0-9_-]+\.[a-zA-Z]+(\/[a-zA-Z0-9]*)*(\/?\?[a-zA-Z0-9]+=[a-zA-Z0-9_-]+(&[a-zA-Z0-9]+=[a-zA-Z0-9_-]+)*)*)#';
  14.  
  15.     $replacement[0] = '<iframe width="560" height="315" src="http://www.youtube.com/embed/$5" frameborder="0" allowfullscreen></iframe>';
  16.     $replacement[1] = '<a href="$1" target="_blank">$1</a>';
  17.    
  18.     preg_match_all($pattern[0], $body, $youtube, PREG_OFFSET_CAPTURE);
  19.     preg_match_all($pattern[1], $body, $hyperlinks, PREG_OFFSET_CAPTURE);
  20.  
  21.     $links = array_merge($youtube[0], $hyperlinks[1]);
  22.    
  23.     usort($links, link_array_sort);
  24.  
  25.     print_r($links);
  26.  
  27.     $output = "";
  28.     if(!empty($links)){
  29.         $match_array_length = count($links);
  30.         $start = 0;
  31.         foreach($links as $key => $value){
  32.             $match_start = $value[1];
  33.  
  34.             $output .= htmlspecialchars(substr($body, $start, $match_start - $start));
  35.  
  36.             if($value[0] == preg_replace($pattern[1], $replacement[1], $value[0])){
  37.                 $output .= preg_replace($pattern[0], $replacement[0], $value[0]);
  38.             }else{
  39.                 if(preg_match("/https?/", $value[0]) == 0) {
  40.                     $subject = 'http://'.$value[0];
  41.                 }else{
  42.                     $subject = $value[0];
  43.                 }
  44.                 $output .= preg_replace($pattern[1], $replacement[1], $subject);
  45.             }
  46.  
  47.             $start = $match_start + strlen($value[0]);
  48.  
  49.             if(($match_array_length - $key) == 1){
  50.                 $output .= substr($body, $start);
  51.             }
  52.         }
  53.         return $output;
  54.     }else{
  55.         return htmlspecialchars($body);
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment