PHP正则表达式在管道分隔的文本中匹配字符串


php regex to match string in pipe delimited text

这是我正在处理的文档中的一个示例行:

    2011-08-08|M|Misc Info|6PM|Away vs. First Words, Second String, Third|Other Info

我想得到"Away vs."和下一个"|"之间的所有内容

使用php的explosion函数来创建数组

$str = "2011-08-08|M|Misc Info|6PM|Away vs. First Words, Second String, Third|Other Info";
$arr = explode($str, '|');

$parts = $arr[4];
$newArr = explode($parts, ',');
$string = '2011-08-08|M|Misc Info|6PM|Away vs. First Words, Second String, Third|Other Info';
$parts = explode('|', $string);
echo $parts[4]; // This is what you are looking for.

我不明白你为什么要在这里使用正则表达式。

如果你使用的是PHP 5.3,还有另一个解决方案:

$parts = str_getcsv($string, '|');
echo $parts[4]; // This should be the part you're looking for

str_getcsv也理解封闭字符串,使其更健壮。