2016-12-29 138 views
0

我正在處理一個項目,其中包含一個包含內容的字符串,例如$content,以及帶有單詞(沒有大寫字母)的數組,例如$rewrites用preg_replace替換大寫字母和非大寫字符串

我想要什麼來實現,例如案例:

$content包含以下文本字符串:「蘋果是蘋果的多,蘋果都好吃」。

$rewrites包含以下數據的數組:「蘋果」,「藍莓」。

現在我想要創建一個函數,將所有蘋果替換爲別的東西,例如覆盆子。但是,在字符串中,有蘋果,它不會被preg_replace替換。應該用樹莓替代蘋果(提到大寫字母R)。

我嘗試了不同的方法和模式,但它不起作用。

目前,我有以下代碼

foreach($rewrites as $rewrite){ 
     if(sp_match_string($rewrite->name, $content) && !in_array($rewrite->name, $spins) && $rewrite->name != $key){ 
     /* Replace the found parameter in the text */ 
     $content = str_replace($rewrite->name, $key, $content); 

     /* Register the spin */ 
     $spins[] = $key; 
     } 
    } 

function sp_match_string($needle, $haystack) { 

if (preg_match("/\b$needle\b/i", $haystack)) { 
    return true; 
} 
return false; 

} 
+0

可能你只需要添加 '蘋果', '藍莓' 你'$ rewrites'陣列? – BizzyBob

+0

@BizzyBob不,這是不可能的。因爲如果我將這些添加到數組中,我不知道是否需要用大寫字母替換它。 – Chiel

+0

我在說要搜索大寫字母並用大寫字母替換。搜索小寫字母並用小寫字母替換。 – BizzyBob

回答

0

我做到了通過建立動態的各種替代的情況。

$content = 'Apples is the plural of apple, apples are delicious'; 

$rewrites = array(
    array('apple', 'blueberry'), 
    array('apple', 'raspberry') 
); 

echo "$content\n"; 
foreach ($rewrites as $rule) { 
    $source = $rule[0]; 
    $target = $rule[1]; 

    // word and Word 
    $find = array($source, ucfirst($source)); 
    $replace = array($target, ucfirst($target)); 

    // add plurals for source 
    if (preg_match('/y$/', $source)) { 
     $find[] = preg_replace('/y$/', 'ies', $source); 
    } else { 
     $find[] = $source . 's'; 
    } 
    $find[] = ucfirst(end($find)); 

    // add plurals for target 
    if (preg_match('/y$/', $target)) { 
     $replace[] = preg_replace('/y$/', 'ies', $target); 
    } else { 
     $replace[] = $target . 's'; 
    } 
    $replace[] = ucfirst(end($replace)); 

    // pad with regex 
    foreach ($find as $i => $word) { 
     $find[$i] = '/\b' . preg_quote($word, '/') . '\b/'; 
    } 

    echo preg_replace($find, $replace, $content) . "\n"; 
} 

輸出:

Apples is the plural of apple, apples are delicious 
Blueberries is the plural of blueberry, blueberries are delicious 
Raspberries is the plural of raspberry, raspberries are delicious 
相關問題