0

I have created a blog in php. Users can post anything like a text, or a link, or youtube link. I use preg_replace() in order my code to determine when there is link or a youtube link. This is what I use:

<?php

//...code


$row['comment'] = preg_replace('@(https?://([-\w.]+[-\w])+(:\d+)?(/([\w-.~:/?#\[\]\@!$&\'()*+,;=%]*)?)?)@', '<a href="$1" target="_blank">$1</a>', $row['comment']);


$row['comment'] = preg_replace("/\s*[a-zA-Z\/\/:\.]*youtube.com\/watch\?v=([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i"," <object width=\"100px;\" height=\"100px;\"><param name=\"movie\" value=\"http://www.youtube.com/v/$1&hl=en&fs=1\"></param><param name=\"allowFullScreen\" value=\"true\"></param><embed src=\"http://www.youtube.com/v/$1&hl=en&fs=1\" type=\"application/x-shockwave-flash\" allowfullscreen=\"true\" width=\"400px;\" height=\"200px;\"></embed></object>",$row['comment']);

  // then prints the $row['comment']

 ?>

my preg_replace() works fine and determines with success when there is link or a youtube link. The only problem is that when there is youtube link posted, It is displayed 2 times...probably because I gave for $row['comment'] 2 different declarations. Any idea how can I get rid of this? Is it better to combine the above 2 statements in 1? and how can I do this? Or any other "if" statement that I can use?

Any idea how to combine the above 2 statements in one?

user2491321
  • 673
  • 10
  • 32

2 Answers2

0

I prefer using the strpos function for checking a string (in your case url). See the PHP.net documentation for more details.

Using an if structure is recommended because you need to do different implementation for every link type. The following StackOverflow question is very useful.

Community
  • 1
  • 1
Ruben
  • 343
  • 2
  • 11
0

The following code will do the trick.

function get_link_type($url)
{
    if(strpos($url, 'youtube') > 0)
    {
        return 'youtube';
    }
    else
    {
        return 'default';
    }
}

$url = 'http://www.google.com/watch?v=rj18UQjPpGA&feature=player_embedded';
$link_type = get_link_type($url);

if($link_type == 'youtube')
{
    $new_link = '<iframe width="560" height="315" src="//'. $url .'" frameborder="0" allowfullscreen></iframe>';
}
else
{
    $new_link = '<a href="'. $url .'">'. $url .'</a>';
}

echo $new_link;
Ruben
  • 343
  • 2
  • 11