2015-11-01 84 views
0

我使用php,我需要用正則表達式拆分字符串(xpath)。 我只需要一個正則表達式來分割下面的「輸入」。我希望有一個人可以幫助我。正則表達式拆分xpath


輸入: /路徑/到/節點/測試

輸出:

$result = array(
    "path", 
    "to", 
    "node", 
    "test", 
); 

輸入: /路徑/到[子= 「string」AND sub2 =「string2」]/node/test

輸出:

$result = array(
    'path', 
    'to[sub="string" AND sub2="string2"]', 
    'node', 
    'test', 
); 

輸入: /路徑/到[子/路徑/要= 「字符串」] /節點/測試

輸出:

$result = array(
    'path', 
    'to[sub/path/to="string"]', 
    'node', 
    'test', 
); 

以前謝謝!

問候 薩沙

+0

嘗試我的編輯和 –

回答

-1

只需使用explode

$str = explode('/',yourString) 

或者,如果你有,你要不理你可以試試下面的正則表達式內/ onnly內[]

preg_match_all("/\[(?:[^\[\]]|(?R))+\]|[^\[\]\/]+/", $input, $matches); 

例如:

$input = '/path/to[sub/path/to="string"]/node/test'; 
preg_match_all("/\[(?:[^\[\]]|(?R))+\]|[^\[\]\/]+/", $input, $matches); 
var_dump($input); 
var_dump($matches); //this will give you expected output 

說明:

我們捕捉2種在這裏:

  1. /\[(?:[^\[\]]|(?R))+\]匹配方括號之間的任何遞歸
  2. [^\[\]\/]+比賽不是由[]
任何字符序列
+1

不,它不會工作w埃爾。 http://melpon.org/wandbox/permlink/MiCPLRelWfEOmuEy – MikeCAT

+0

@MikeCAT嘗試替代正則表達式 –

+0

通過新的正則表達式,「」到「和」「[sub/path/to =」string「]」'被分割,但在實際中他們不是。 http://melpon.org/wandbox/permlink/JEQfPQEKgJfzLhHt – MikeCAT