2016-02-22 29 views
0

說我有這些字符串PHP的:檢測單字母由特殊字符引起來的字符串

tavern-o-fallon-new-york 
cut-n-shoot-texas 
cut-n-shoot-texas-at-o-fellon 

我想檢測-O-,或任何其他模式的所有事件,並轉換爲'0「

,所以我可以將字符串轉換爲

Tavern O'Fallon New York 
Cut'N'Shoot Texas 
Cut'N'Shoot Texas At O'Fellon 

相信我可以使用像將O常見模式的一些陣列」,‘N’等。

+0

'S/- (。 ) -/\ 1' /'?這個將會在'建造一個熊' - >'建立一個'熊'上炸彈。 –

+0

@MarcB謝謝...是的...可以工作,但說我有法國或意大利的城市,所以它實際上不是一個單一的字母? – Francesco

+0

那麼你可能不希望正則表達式,或者至少,不是一個正則表達式。正則表達式適用於常規文本。如果你的輸入是不規則的,那麼你不能真正使用它們的REGULAR表達式。 –

回答

1

I`d使用str_replace函數:

$phrase = 'tavern-o-fallon-new-york 
cut-n-shoot-texas 
cut-n-shoot-texas-at-o-fellon'; 
$phrase = str_replace(array('-n-','o-','-'),array('`N`','O`',' '), $phrase); 
echo ucwords($phrase); 

輸出:

Tavern O`fallon New York 
Cut`N`shoot Texas 
Cut`N`shoot Texas At O`fellon 

編輯:

要解決的小寫字母:

$phrase = str_replace(array('-n-','o-','-'),array('`N` ','O` ',' '), $phrase); // add an extra space after the quote; 
$phrase = ucwords($phrase); //then ucfirst can do the job 
$phrase = str_replace('` ','`', $phrase); //remove the extra space 
echo $phrase; 
+1

人們總是會被他們忘記的正則表達式簡單的東西;-) –

+0

我知道這種感覺:)) –

相關問題