2013-02-15 73 views
-1

我想用另一个替换数据库(wordpress)中的一些URL,但这很棘手,因为很多URL都是重定向。我试图根据结果来将网址替换为重定向的网址或我选择的网址。我可以在没有任何问题的情况下完成匹配,但我无法替换它。我试过str_replace,但它似乎并没有取代网址。当我尝试preg_replace时,它会给出“警告:preg_replace():分隔符不能是字母数字或反斜杠”。任何人都可以用正确的方式指出我做到这一点吗?用另一个替换一个URL而不用正则表达式

if(preg_match($url_regex,$row['post_content'])){ 
    preg_match_all($url_regex,$row['post_content'],$matches); 

    foreach($matches[0] as $match){ 
     echo "{$row['ID']} \t{$row['post_date']} \t{$row['post_title']}\t{$row['guid']}"; 

     $newUrl = NULL; 
     if(stripos($url_regex,'domain1') !== false || stripos($url_regex,'domain2') !== false || stripos($url_regex,'domain3') !== false){ 
      $match = str_replace('&','&',$match); 

      $ch = curl_init(); 
      curl_setopt($ch,CURLOPT_URL,$match); 
      curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); 
      curl_setopt($ch, CURLOPT_HEADER, true); 
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
      $html = curl_exec($ch); 
      $newUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); 

      if(stripos($newUrl,'domain4') !== false) 
       $newUrl = NULL; 

     } 
     else 

     if($newUrl == NULL) 
     { $newUrl = 'http://www.mysite.com/'; 

     } 
     echo "\t$match\t$newUrl"; 
     $content = str_replace($match,$newUrl,$row['post_content']); 
     echo "\t (" . strlen($content).")"; 
     echo "\n"; 

    } 
} 
+1

re error:“警告:preg_replace():分隔符不能是字母数字或反斜杠” - 向我们显示正则表达式。听起来就像你刚刚在表达式中缺少// [[delimiters](http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php))。 – ficuscr 2013-02-15 19:22:41

+0

如果我使用它而不是接近底部的str_replace,则会出现preg_replace错误。 preg_replace函数($匹配,$ NEWURL,$行[ 'POST_CONTENT']); – aynber 2013-02-15 19:24:22

+0

为什么你不能使用正则表达式来做替换?有问题,但在文本中没有解释。 – Thronk 2013-02-15 19:24:51

回答

1

这就是你如何处理Perl正则表达式。

$baesUrlMappings = array('/www.yoursite.com/i' => 'www.mysite.com', 
         '/www.yoursite2.com/i' => 'www.mysite2.com',); 

echo preg_replace(array_keys($baesUrlMappings), array_values($baesUrlMappings), 'http://www.yoursite.com/foo/bar?id=123'); 
echo preg_replace(array_keys($baesUrlMappings), array_values($baesUrlMappings), 'http://www.yoursite2.com/foo/bar?id=123'); 

http://codepad.viper-7.com/2ne7u6

请阅读使用说明书!你应该能够弄清楚这一点。

+0

唉,没有。我在你的代码中粘贴了我的URL,它出错了。 – aynber 2013-02-15 19:55:34

+0

唉,如果您无法自己回复错误,请发布错误,阅读说明书或以其他方式提供有用的信息,这些信息使您很难帮助您。 ESP告诉我它可能需要跳过正则表达式模式中的字符串...... – ficuscr 2013-02-15 19:59:17

+0

对不起,我正在玩那个页面上的代码。用/定界符,它给了“警告:preg_replace():未知修饰符'/'”。当然,它会与URL中的所有/。用@分隔符,我没有收到错误,但它也没有替换URL。 – aynber 2013-02-15 20:01:01

相关问题