2013-03-20 126 views
-1

我想用給定的格式替換特定的字符串。請參閱突出顯示的詞組以獲得差異。替換字符串中的短語

1967年,瑜珈普拉,「15440 N.街7號套房1」,亞利桑那州鳳凰城,85022,-112.066286,33.627028,26'

進入

1967年,普拉瑜伽,15440 N. 7th Street Suite 1,Phoenix,AZ,85022,-112.066286,33.627028,26'

我試圖刪除由雙qoutes包含的短語中的逗號。我知道如何替換它,但我不知道如何設置這個短語「15440 N. 7th Street,Suite 1」 in a variable。

$lines = preg_replace('/"[^"]+"/', 'new formatted text', $lines); 

請幫

+3

因此,換句話說,你有一個CSV行,你想使每一列逗號自由(和報價解開)? – 2013-03-20 07:27:49

+0

是的,你是100%正確 – 2013-03-20 07:28:54

+0

您的示例輸入和輸出與描述不符。你想刪除雙引號,或逗號,或兩者? – meagar 2013-03-20 07:28:56

回答

2

另一種方式與正則表達式來做到這一點:

$str = '67,Yoga Pura,"15440 N. 7th Street, Suite ",Phoenix,AZ,85022,-112.066286,33.627028,26'; 
echo preg_replace ('#"(.*?),(.*?)"#', '$1$2', $str); 

輸出:

67,Yoga Pura,15440 N. 7th Street Suite 1,Phoenix,AZ,85022,-112.066286,33.627028,26 
0

您可以使用前瞻

/,(?=(([^"]*"[^"]*"[^"]*[^"]*"[^"]*)+|[^"]*"[^"]*)$)/ 
     ---------------------------- _ ---------- 
        |     |  |->matches a single odd " till end 
        |     |->OR 
        |-> matches 1 to many occurrences of 3 " till end 

所以這會匹配,只有同時具備奇數其次它的"


Obviousl Ÿ這不會對工作嵌套"

1

可以匹配所有雙引號之間的部分,然後用一個回調函數來剝離雙引號/從他們逗號:

$string = '67,Yoga Pura,"15440 N. 7th Street, Suite 1",Phoenix,AZ,85022,-112.066286,33.627028,26'; 

function strip_commas($str) { 
    return str_replace(array(',', '"'), '', $str[0]); 
} 

$string = preg_replace_callback('/".*?"/', "strip_commas", $string); 
1

試試這個:

$text = preg_replace('/^(.*)"([^"]*),([^"]*)"(.*)$/', '${2}${3}', $text); 

的部分"之間隔離和刪除您,

或本:

$text = preg_replace('/"([^"]*),([^"]*)"/', '${1}${2}', $text); 

只是爲了去除",之間。

它似乎運作良好

working example here

0

有可能是一些速記回調片「東經爲此,合併單線奇蹟,但我們直接做:

$row = '67,Yoga Pura,"15440 N. 7th Street, Suite 1",Phoenix,AZ,85022,-112.066286,33.627028,26'; 
$parsed = str_getcsv($row); 
$parsed2 = array(); 
$i = 0; 

while ($col = array_shift($parsed)) { 
    array_push($parsed2, str_replace(',', '', $col)); 
} 

https://ignite.io/code/51496970ec221ee821000003

當然,這是使用str_getcsv(),最簡單的方法來分析從一個字符串CSV行(如果你有PHP> = 5.3.0)中。

稍短:

$row = '67,Yoga Pura,"15440 N. 7th Street, Suite 1",Phoenix,AZ,85022,-112.066286,33.627028,26'; 
$parsed = str_replace(',', '', str_getcsv($row)); 

print_r($parsed); 

echo implode(',', $parsed); 

https://ignite.io/code/51496b2bec221ee821000004