2013-08-02 116 views
2

我正在使用具有自定義PHP函數的數據饋送插件,該函數允許我重寫Feed中的每個Buy_URL。說,例如,原來的Buy_URLs之一是這樣的:我應該使用str_replace而不是substr?

http://www.affiliatecompa.com/product/clean.com?ref=ab 

我想重寫開始和URL與

http://www.dsqce.com/click-111111-1111XX111?url=http%3A%2F%2Fwww.affiliatecompa.com

「結束laik「`分別。所以,它應該成爲:

http://www.dsqce.com/click-111111-1111XX111?url=http%3A%2F%2Fwww.affiliatecompa.com/product/clean.com?ref=laik 

我聯繫插件的作者,他告訴我把下面的代碼function.php在我的主題,然後調用該函數在插件

function WOKI_Change_Url($x){ 
    $y = substr($x, 29); 
    $y = substr($y, -2); 
    return "http://www.dsqce.com/click-111111-1111XX111?url=http%3A%2F%2Fwww.affiliatecompa.com" . $y . 'laik'; 
} 

顯然,這是行不通的,因爲它消除了URL的任何其他部分,現在每Buyurl已成爲

http://www.dsqce.com/click-111111-1111XX111?url=http%3A%2F%2Fwww.affiliatecompa.comlaik 

我懷疑SUBSTR是不正確的什麼我想在這種情況下做的。我應該在函數中使用str_replace嗎?

+0

檢查出的功能:[parse_url](http://www.php.net/manual/en/function.parse-url.php),[parse_str](HTTP:// WWW .php.net/manual/en/function.parse-str.php)和[http_build_query](http://www.php.net/manual/en/function.http-build-query.php) – bitWorking

回答

0

str_replace()可以適合你正在嘗試做的事情,但他的方法也可以工作。他只是在substr()上忽略了一個參數。他的代碼應與參數工作添加回(假設你總是在字符串的ref=ab部分2字符值:

function WOKI_Change_Url($x){ 
    $y = substr($x, 29); 
    $y = substr($y, 0, -2); //the 0 here tells it to use the whole string, minus the last two chars; without the zero, this would muck things up a lot 
    return "http://www.dsqce.com/click-111111-1111XX111?url=http%3A%2F%2Fwww.affiliatecompa.com" . $y . 'laik'; 
} 

至於str_replace(),這也可以,如果你知道的值工作你試圖取代,但事情變得複雜起來使用str_replace函數轉義如果它總是與ref=laik那麼下面應該工作(使用urlencode()進行轉義)來代替準確ref=ab

function WOKI_Change_Url($x){ 
    $y = str_replace($x, "ref=ab", "ref=laik"); //this replaces the ref=ab part 
    return "http://www.dsqce.com/click-111111-1111XX111?url=http%3A%2F%2Fwww.affiliatecompa.com" . urlencode($y); 
} 

注意如果你不確定它將始終是您要替換的ab,您可能需要使用preg_replace,而使用正則表達式來替換在ref=之後出現的任何內容。類似:

function WOKI_Change_Url($x){ 
    $y = preg_replace("/ref=.*/", "ref=laik", $x); //this replaces the ref= part for anything... but I haven't tested it 
    return "http://www.dsqce.com/click-111111-1111XX111?url=http%3A%2F%2Fwww.affiliatecompa.com" . urlencode($y); 
} 
+0

我很感謝你幫幫我。我嘗試了他們,但不幸的是,他們都沒有工作。 substr()只是把「http://www.dsqce.com/click-111111-1111XX111?url=http%3A%2F%2Fwww.affiliatecompa.com」和「laik」放在一起,而不是重寫開頭和結尾網址。 preg_replace和str_replace()只需將整個URL替換爲「http://www.dsqce.com/click-111111-1111XX111?url=http%3A%2F%2Fwww.affiliatecompa.com」。我會繼續努力的。謝謝。 – RedGiant

+0

我開始認爲有些東西阻止源url作爲參數傳遞給函數。你能用一個相關代碼的例子來更新這個問題嗎?在那裏調用'WOKI_Change_Url'函數?你描述的行爲適合於如果'$ x'沒有價值會發生什麼。 –

+0

您可以通過在每個函數的第一行添加'echo $ x;'來驗證,或者如果這樣做不起作用,可以在某些測試中使用'return $ x;'來查看函數對於源的值網址。 –

相關問題