2015-10-05 108 views
2

我試圖找到正確的正則表達式替換雙引號時,逗號,的preg_replace雙引號不是逗號後

後不是在下面的字符串,只有當它涉及經過一番刪除一個雙引號字符,這不是定界符/逗號

"ahys"", "hshs","", "277-"" 

上面的字符串改變此之後preg_replace

"ahys", "hshs","", "277-" 

我使用這個模式,但它不工作 - 它不僅取代引號也從左側一個字符

​​

結果:

「AHY」,「hshs」 「」,「277」

誰能告訴我我的模式在這裏有什麼問題嗎?

+2

'[^ 「」]'表示 「不報價,而不是逗號」。 ''''''''''''''''''''''''''''''''''''' –

+0

只是將「」替換爲「 –

+0

@MarcB得到了它的謝謝,但我的問題仍然存在 – Muhammad

回答

2

也許這樣的:

(?<!^|,\s|,)"(?!,|$) 

https://regex101.com/r/cE2yD0/1

它使用lookarounds找到" s表示符合以下標準:

  • 不是在一個字符串的開頭或結尾

  • 未先或成功由, ceeded(與"之前可選空間)

1

,如果你不」想要使用正則表達式lookarounds那麼你可以使用這樣的正則表達式:

("[\w-]+?")" 

隨着替換字符串:

$ 

Working demo

代碼

$re = '/("[\w-]+?")"/'; 
$str = "\"ahys\"\", \"hshs\",\"\", \"277-\"\"\n"; 
$subst = "$1"; 

$result = preg_replace($re, $subst, $str); 
+0

只要只有一個封閉的「它與臨近的閉合」,這很好地工作。但這可能符合OP的要求。 – lintmouse

+0

@dustmouse是的,因爲可能是這樣,所以公佈了你的答案。 –

+0

肯定。這是一個很好的免看方案。 – lintmouse

0

您還可以使用str_replace函數這是更快

<?php 

    $str = 'test one -> " <- removed, not -> ", <- removed, not -> ," <- removed' 

    echo str_replace(array('",', ',"', '"', '%@@%,', ',%@@%'), array('%@@%,', ',%@@%', '', '",', ',"'), $str); 

    // prints test one -> <- removed, not -> ", <- removed, not -> ," <- removed 

?>