0

This is an example line in the document I am processing:

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

I would like to get everything between "Away vs." and the next "|"

3
  • 1
    Will the document always be in a similar format? Also, how will missing data be handled in this format? Commented Aug 9, 2011 at 0:03
  • 2
    What regex were you using so far? What's your code so far? Into which problem did you run? Or are you just asking for code? Commented Aug 9, 2011 at 0:04
  • That looks pipe-separated, not pipe-delimited. Which did you mean? |a|b|c| has three three fields if pipe-delimited and five fields if pipe separated. Commented Aug 9, 2011 at 0:13

2 Answers 2

1

Just use php's explode function to make an array.

$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, ',');
Sign up to request clarification or add additional context in comments.

1 Comment

Explode may not do well if he is processing large chunks of data. Also, this would give him several unnecessary arrays - he only needs a string extracted from his format.
1
$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.

I don't see why you would use regexes here.

If you are using PHP 5.3 there's another solution:

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

str_getcsv also understands enclosed strings, making it more robust.

1 Comment

I had tried something that did strpos() until it reached the correct pipe, but a test showed that it was considerably slower than this solution. +1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.