【问题标题】:preg_replace_callback - I need this to ignore spaces in URL for duplicatespreg_replace_callback - 我需要这个来忽略重复的 URL 中的空格
【发布时间】:2012-06-19 23:25:51
【问题描述】:

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

http://domain.com/1.jpg

http://domain.com/1http://(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);
?>

【问题讨论】:

    标签: php


    【解决方案1】:

    网址中不应有空格。见Spaces in URLs?。一个简单的解决方法是在 preg_match 之前对其进行 url 编码。

    您应该对内容进行 urlencode,但既然您已经存储了它,请尝试这样做

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

    【讨论】:

    • 这似乎没有任何作用。
    • 当用户上传一张图片时,它会将 URL 发布到数据库中。如果它是重复的图像,它将变为 domain.com/..dirs/image.jpg (1).jpg ... 重复中的空间似乎导致上述代码将其拆分为两个 url。您发布的代码位于 preg_match 行的正上方,它会进行任何更改。
    • 你能更正你的粘贴吗?它有三个 { 和两个 },所以很难弄清楚发生了什么
    • 所有困难的方法和挖掘,就这么简单吧?谢谢 jpiasetz。
    猜你喜欢
    • 2011-02-07
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 2016-01-28
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多