Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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.
- <?php
- function link_array_sort($a, $b){
- if($a[1] == $b[1]){
- return 0;
- }
- return ($a[1] < $b[1]) ? -1 : 1;
- }
- function string_to_links_and_embedded($body){
- $pattern[0] = '#(http:\/\/)?(www\.)?youtube\.com/watch\?((&?v=([a-zA-Z0-9_-]+))|(&?[a-zA-Z0-9_-]+=[a-zA-Z0-9_-]+))*#';
- $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_-]+)*)*)#';
- $replacement[0] = '<iframe width="560" height="315" src="http://www.youtube.com/embed/$5" frameborder="0" allowfullscreen></iframe>';
- $replacement[1] = '<a href="$1" target="_blank">$1</a>';
- preg_match_all($pattern[0], $body, $youtube, PREG_OFFSET_CAPTURE);
- preg_match_all($pattern[1], $body, $hyperlinks, PREG_OFFSET_CAPTURE);
- $links = array_merge($youtube[0], $hyperlinks[1]);
- usort($links, link_array_sort);
- print_r($links);
- $output = "";
- if(!empty($links)){
- $match_array_length = count($links);
- $start = 0;
- foreach($links as $key => $value){
- $match_start = $value[1];
- $output .= htmlspecialchars(substr($body, $start, $match_start - $start));
- if($value[0] == preg_replace($pattern[1], $replacement[1], $value[0])){
- $output .= preg_replace($pattern[0], $replacement[0], $value[0]);
- }else{
- if(preg_match("/https?/", $value[0]) == 0) {
- $subject = 'http://'.$value[0];
- }else{
- $subject = $value[0];
- }
- $output .= preg_replace($pattern[1], $replacement[1], $subject);
- }
- $start = $match_start + strlen($value[0]);
- if(($match_array_length - $key) == 1){
- $output .= substr($body, $start);
- }
- }
- return $output;
- }else{
- return htmlspecialchars($body);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment