preg_replace_callback - 我需要它来忽略 URL 中的重复空格


preg_replace_callback - I need this to ignore spaces in URL for duplicates

这是我用来解析URL的当前代码,它适用于MySQL中的所有查询,直到它到达URL中的一个空格。然后它只是像这样将事情分开。

http://domain.com/1.jpg

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

我需要解决这个问题。

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

URL 中永远不应该有空格。请参阅 URL 中的空格?。一个简单的解决方法是在preg_match之前对其进行 url 编码。

你应该对东西进行编码,但由于你已经存储了它,请尝试这样做

$str = str_replace(' ', '%20', $str);
$str = preg_replace_callback('#(?:https?://'S+)|(?:www.'S+)|(?:'S+'.'S+)#', function($arr)