2016-02-18 57 views
0

好的,我認爲此頁面上的搜索欄中斷的原因是因爲PHP已更新,而preg_replace已棄用。 https://sparklewash.com/使用Preg_Replace_Callback函數

我試過將preg_replace函數替換爲preg_replace_callback像這樣,但我仍然遇到一些問題。

原文:

function clean($string) { 
    $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens. 
    return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars. 

} 

新版本:

function clean($string) { 
    $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens. 
    return preg_replace_callback('/(^|_)([a-z])/', 
    create_function ('$matches', 'return strtoupper($matches[2]);'), $string); // Removes special chars. 
} 

我道歉,如果這是很容易爲你,我試圖遵循這裏的文章,但我仍然PHP相對較新。

編輯:我相信preg_replace不是因爲某些評論而破壞它。我在這裏提出了一個新的問題,留在主題:Redirect Loop on $_GET Request

+2

'preg_replace'不棄用'e'修改是。你在用什麼?包含您以前的錯誤消息和代碼.. – chris85

+0

您使用的是哪個版本的PHP?如果您使用的是5.3.0或更新的版本,則應該使用匿名函數而不是'create_function()'。 – Barmar

+0

我不明白這個問題。原始代碼沒有使用'strtoupper',爲什麼你需要更新? – Barmar

回答

0

我不會推薦您使用的語法,錯誤的最可能的原因,請嘗試下面的語法。

$result = preg_replace_callback('/(^|_)([a-z])/', function($matches){ 

    return strtoupper($matches[0]); 
    /* 
    $matches[0] is the complete match of your regular expression 
    $matches[1] is the match of the 1st round brackets() similarly for $matches[2]...and so on. 

    */ 

}, $string); 

//Also $result will contain the resultant string 

您必須將$匹配到您的回調函數,您也可以單獨聲明回調函數作爲獨立函數。

function make_upper($matches){ 

    return strtoupper($matches[0]); 

} 
$result = preg_replace_callback('/(^|_)([a-z])/','make_upper' , $string); 

希望我的解決方案能爲您工作,謝謝。 :)

相關問題