分裂字符串时遇到麻烦

时间:2011-11-26 16:55:14

标签: php regex

我实际上有一些字符串有一些由管道字符分隔的数据,例如:

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)

?>

1 个答案:

答案 0 :(得分:3)

你需要双重转义反斜杠,因为它们被解析了两次:一个是字符串解析器,一个是正则表达式引擎。

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