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;
}
可能你只需要添加 '蘋果', '藍莓' 你'$ rewrites'陣列? – BizzyBob
@BizzyBob不,這是不可能的。因爲如果我將這些添加到數組中,我不知道是否需要用大寫字母替換它。 – Chiel
我在說要搜索大寫字母並用大寫字母替換。搜索小寫字母並用小寫字母替換。 – BizzyBob