2
实际上,我有一些字符串必须用管道字符分隔的一些数据,例如字符串:故障而分裂
One | Two | Three
我想,当我找到一个管道拆分这些字符串,但我也要确保如果有“逃脱的管道”(\ |),它将不会被处理。
因此,举例来说,从这个字符串:Tom | Dick \| and | Harry
我想获得一个包含值的数组:Tom
,Dick \| and
,Harry
为此,我写了一个小的正则表达式,搜索一管道的前面没有反斜杠:(?<!\\)\|
我测试了这个正则表达式在我的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)
?>
非常感谢:-) – Cesco