2011-02-14 74 views
0

我正在使用谷歌翻譯api的一些簡單的東西,但是當翻譯英語到其他語言它有時會給我間空格之間的引號,所以有人可以給我一個正則表達式匹配語句在PHP中取代空間在報價單和第一個單詞以及報價單和最後一個單詞之間?php - 正則表達式匹配問題

實例翻譯的短語: 字字字「constructie在隆登」字字字

我想正則表達式將其轉換爲: 字字字「constructie在隆登」字字字

謝謝!

+0

是否保證不會有無與倫比的引號? – GWW 2011-02-14 03:52:59

+0

不確定你的意思,有些短語可能有引號,有些短語可能不會。所以如果沒有匹配的引號,顯然正則表達式不會對字符串做任何事情。 – Joe 2011-02-14 03:55:21

回答

1

這是一種模式:"\s*(.*?)\s*"

$str = 'word word word " constructie in Londen " word word word'; 
$newStr = preg_replace('/"\s*(.*?)\s*"/', '"\\1"', $str); 
echo $newStr; 
// word word word "constructie in Londen" word word word 

這也將有多個報價段工作:

$str = 'word word word " constructie in Londen " word word wordword word word " constructie in Londen " word word wordword word word " constructie in Londen " word word word'; 
$newStr = preg_replace('/"\s*(.*?)\s*"/', '"\\1"', $str); 
echo $newStr; 
// word word word "constructie in Londen" word word wordword word word "constructie in Londen" word word wordword word word "constructie in Londen" word word word 

或者你可以使用/e修正與微調:

$str = 'word word word " constructie in Londen " word word wordword word word " constructie in Londen " word word wordword word word " constructie in Londen " word word word'; 
$newStr = preg_replace('/"(.*?)"/e', "'\"'.trim('\\1').'\"'", $str); 
echo $newStr; 
// word word word "constructie in Londen" word word wordword word word "constructie in Londen" word word wordword word word "constructie in Londen" word word word 

編輯 t o使用菲爾布朗的建議。

編輯使用艾倫摩爾的建議。