Help parsing a large group of text for certain values?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: Help parsing a large group of text for certain values?

Post by McInfo »

Sorry to interrupt. I wrote a function because I think this problem is general enough that the solution could be useful to many people. The function is a little fragile (meaning non-standard input results in weird output), but I'll just release it now because I don't think I will have a chance to make it more robust in the near future. It has not been thoroughly tested.

Code: Select all

<?php
/**
 * Splits a string on multiple, sequential delimiters. Works like explode(),
 * but with an array of delimiters.
 *
 * @param array $delimiters
 * @param string $subject
 * @return array of values
 */
function fragmentize ($delimiters, $subject) {
    $values = array();
    $cpos = 0;
    $count = count($delimiters);
    for ($i = 0; $i < $count; ++$i) {
        $curr = $delimiters[$i];
        $cpos = strpos($subject, $curr, $cpos) + strlen($curr);
        $next = ($i < $count - 1) ? $delimiters[$i + 1] : null;
        $npos = ($next) ? strpos($subject, $next, $cpos) : strlen($subject);
        $values[$i] = trim(substr($subject, $cpos, $npos - $cpos));
    }
    return $values;
}

//------------------------------------------------------------------------------
// Usage:

$string = 'Help Number: 125086 ENTERED ON 11/29/10 AT 14:33 BY JOHN SMITH CURRE'
    . 'NT ESTIMATED COMPLETION IS 12/06/10 AT 15:00 TYPE OF PROBLEM: T.P. BIG I'
    . 'SSUE PRIORITY: 5 WORKING DAYS ITEM SUBMITTED BEFORE? NO ------------ PRO'
    . 'BLEM DESCRIPTION ------------ SOME LONG DESCRIPTION';
echo wordwrap($string, 80), "\n";

$delimiters = array (
    'Help Number:',
    'ENTERED ON',
    'AT',
    'BY',
    'CURRENT ESTIMATED COMPLETION IS',
    'AT',
    'TYPE OF PROBLEM:',
    'PRIORITY:',
    'ITEM SUBMITTED BEFORE?',
    '------------ PROBLEM DESCRIPTION ------------'
);
print_r($delimiters);

$values = fragmentize($delimiters, $string);
print_r($values);
/*
Array
(
    [0] => 125086
    [1] => 11/29/10
    [2] => 14:33
    [3] => JOHN SMITH
    [4] => 12/06/10
    [5] => 15:00
    [6] => T.P. BIG ISSUE
    [7] => 5 WORKING DAYS
    [8] => NO
    [9] => SOME LONG DESCRIPTION
)
*/
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Help parsing a large group of text for certain values?

Post by Jonah Bron »

Sweet, bookmarked :)
Insyderznf
Forum Newbie
Posts: 11
Joined: Fri Sep 10, 2010 5:08 pm

Re: Help parsing a large group of text for certain values?

Post by Insyderznf »

Nice function, that really helps!
Post Reply