2012-06-01 37 views
1

我有一個字符串,其中每個單詞的所有開頭都大寫。現在我想過濾它,就像它可以檢測到鏈接「as,the,in,etc」一樣,它將被轉換爲小寫。我有一個替代,並將其轉換爲小寫代碼,但1個字只有象下面這樣:在PHP中對字符串進行過濾字詞

$str = "This Is A Sample String Of Hello World"; 
$str = preg_replace('/\bOf\b/', 'of', $str); 

output: This Is A Sample String of Hello World 

所以我想那是什麼過濾換句話說,例如像「是,是」字符串。奇怪的是重複preg_replace每個單詞來過濾。

謝謝!

+0

......把所有單詞合併成一個正則表達式也很奇怪。 –

回答

3

使用preg_replace_callback()

$str = "This Is A Sample String Of Hello World"; 
$str = ucfirst(preg_replace_callback(
     '/\b(Of|Is|A)\b/', 
     create_function(
      '$matches', 
      'return strtolower($matches[0]);' 
     ), 
     $str 
    )); 
echo $str; 

Displays "This is a Sample String of Hello World".

+0

+1不錯的解決方案:-) – ManseUK

+1

但是......如果他們是一個句子的開頭,它會殺死那3個詞。 http://codepad.org/EGzKj1E3 – starlocke

+0

這很容易通過運行[ucfirst()](http://php.net/manual/en/function.ucfirst.php)來解決。 – Jeroen

1

試試這個:

$words = array('Of', 'Is', 'A', 'The'); // Add more words here 

echo preg_replace_callback('/\b('.implode('|', $words).')\b/', function($m) { 
    return strtolower($m[0]); 
}, $str); 


// This is a Sample String of Hello World 
3

既然你知道確切的詞和格式,你應該使用str_replace而不是preg_replace函數;它快得多。

$text = str_replace(array('Is','Of','A'),array('is','of','a'),$text); 
+0

這確實是一個非常好的解決方案! – Jeroen