2011-11-26 94 views
2

實際上,我有一些字符串必須用管道字符分隔的一些數據,例如字符串:故障而分裂

One | Two | Three 

我想,當我找到一個管道拆分這些字符串,但我也要確保如果有「逃脫的管道」(\ |),它將不會被處理。

因此,舉例來說,從這個字符串:Tom | Dick \| and | Harry

我想獲得一個包含值的數組:TomDick \| andHarry

爲此,我寫了一個小的正則表達式,搜索一管道的前面沒有反斜槓:(?<!\\)\|

我測試了這個正則表達式在我的IDE(PHPStorm,這是基於Java的AFAIK)裏面,它工作正常,但是當我在PHP項目中使用它時,米得到錯誤;實際上,我正在使用PHP版本5.3.6測試此代碼。

請問您可能幫助我並告訴我我做錯了什麼?

<?php 

$cText = "First choice | Second \| choice |Third choice"; 

// I need to split a string, and to divide it I need to find 
// each occurrence of a pipe character "|", but I also have to be sure not 
// to find an escaped "|". 
// 
// What I'm expecting: 
// acChoice[0] = "First choice " 
// acChoice[1] = " Second \| choice " 
// acChoice[2] = "Third choice" 

$acChoice = preg_split("/(?<!\\)\|/", $cText); 

// Gives this error: 
// Warning: preg_split(): Compilation failed: missing) at offset 8 in - on line 14 bool(false) 

$acChoice = mb_split("/(?<!\\)\|/", $cText); 

// Gives this error: 
// Warning: mb_split(): mbregex compile err: end pattern with unmatched parenthesis in - on line 19 bool(false) 

?> 

回答

3

您需要雙擊逃脫你反斜線,因爲他們要解析兩次:一個由字符串分析器,然後再一個正則表達式引擎。

$acChoice = preg_split("/(?<!\\\\)\\|/", $cText); 
+0

非常感謝:-) – Cesco