2013-01-21 43 views
0

我有這樣的表達:正則表達式替換整個單詞在PHP

$x="We have a cat here."; 

我想將「A」與,例如5,所以這應該是這樣的:

We have 5 cat here. //It doesn't make sense, but it's just an example. 

我試圖簡單

echo str_replace("a","5",$x); 

但返回

We h5ve 5 c5t here. 

然後,我試過

echo str_replace(" a "," 5 ",$x); 

,但沒有對字符串做的工作就像

We have a cat here. (A dog actually). 

我決定使用正則表達式,但是我完全新手到這一點,我不不知道如何使用它們... 那麼,我真的很感激任何鏈接到一個很好的教程,但我需要的答案相當快...

回答

4

使用\b去除字的限制es,例如

$newstring = preg_replace('/\b[Aa]\b/', '5', $string); 
+0

這就是我的意思。謝謝!在10分鐘內接受... –

+0

也許你知道任何使它適用於UTF8字符的方法,如ąęć等等?我的意思是,如果我用「x」替換所有「a」的出現,我已將「zapłać」更改爲「zapłxć」,並且我希望它與原始文本相同... –

+0

'/ u'修飾符將啓用unicode:http://php.net/manual/en/reference.pcre.pattern.modifiers.php(搜索'PCRE_UTF8')。 –