0

Here is the current code I am using to parse the URL and it's working for all the queries in MySQL until it hits a space in the url. Then it just separates things out like this.

http://domain.com/1.jpg

http://domain.com/1 http://(1).jpg

I need a work around for this.

<?php
$con = mysql_connect("localhost","----","----");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("----", $con);

$result = mysql_query("SELECT * FROM posts ORDER BY postid DESC");

while($row = mysql_fetch_array($result))
  {

$str = $row['post_content'];

$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);

echo $str;
echo "<br />";
}

mysql_close($con);
?>
Dadsquatch
  • 566
  • 5
  • 16

1 Answers1

4

Url's should never have spaces in them. See Spaces in URLs?. A simple work around is to url encode it before the preg_match.

You should urlencode stuff but since you've already stored it try doing

$str = str_replace(' ', '%20', $str);

$str = preg_replace_callback('#(?:https?://\S+)|(?:www.\S+)|(?:\S+\.\S+)#', function($arr)
Community
  • 1
  • 1
jpiasetz
  • 1,692
  • 4
  • 21
  • 35
  • That didn't seem to do anything. – Dadsquatch Jun 17 '12 at 22:54
  • What is happening is when the user uploads an image it posts the url to the database. If it's a duplicate image it becomes domain.com/..dirs/image.jpg (1).jpg ... The space in the duplicates seems to cause the above code to split it into two urls. The code you posted was placed right above the preg_match line and it make any changes. – Dadsquatch Jun 17 '12 at 22:56
  • Can you correct your paste. It's got three { and two } so it's hard to figure out what's going on – jpiasetz Jun 17 '12 at 22:58
  • All the difficult ways of doing it and digging, it was this simple huh? Thanks jpiasetz. – Dadsquatch Jun 18 '12 at 02:39