<?php
function get_chapter($text, $terms) {
	
	if (empty($text)) return;
    if (empty($terms) || !is_array($terms)) return;

    $values = false;

    $terms_quoted = array();
    //make e.g. "chapters" match either "c" OR "Chapters" 
    foreach ($terms as $term)
    	//revert this to your previous one if you want the "terms" provided explicitly
        $terms_quoted[] = $term[0].'('.preg_quote(substr($term,1), '/').')?';
        
	$matcher = '/(('.implode('|', $terms_quoted).')\s*(\d+(?:\s*[&+,.-]*\s*?)*)+)+/i';
    
    //match the "chapter" expressions you provided
    if (preg_match($matcher, $text, $matches)) {
        if (!empty($matches[0])) {
        	
        	//extract the numbers, in order, paying attention to existing hyphen/range identifiers
            if (preg_match_all('/\d+(?:\.\d+)?|-+/', $matches[0], $numbers)) {
                $bot = NULL;
                $top = NULL;
                $nextIsTop = false;
                $results = array();
                $setv = function(&$b,&$t,$v){$b=$v;$t=$v;};
                $flatten = function(&$b,&$t,$n,&$r){$x=$b;if($b!=$t)$x=$x.'-'.$t;array_push($r,$x);$b=$n;$t=$n;return$r;};
                foreach ($numbers[0] as $num) {
                	if ($num == '-') $nextIsTop = true;
                	elseif ($nextIsTop) {
						$top = $num;
						$nextIsTop = false;
                	}
                	elseif (is_null($bot)) $setv($bot,$top,$num);
                	elseif ($num - $top > 1) $flatten($bot,$top,$num,$results);
                	else $top = $num;
                }
				return implode(' & ', $flatten ($bot,$top,$num,$results));
            }
        }
    }
}


$text = array('9 text chapter 25.6 text', // c25.6
'text chapter 25.6 text', // c25.6
'text chapters 23, 24, 25 text', // c23-25
'chapters 23+24+25 text', // c23-25
'chapter 23, 25 text', // c23 & 25
'text chapter 23 & 24 & 25 text', // c23-25
'text c25.5-30 text', // c25.5-30
'text c99-c102 text', // c99-102
'text chapter 99 - chapter 102 text', // c99-102
'text chapter 1 - 3 text', // c1-3
'33 text chapter 1, 2 text 3', // c1-2
'text v2c5-10 text', // c5-10
'text chapters 23, 24, 25, 29, 31, 32 text', // c23-25 & 29 & 31-32
);
$terms = array('chapter', 'chapters');
foreach ($text as $snippet)
{
	$chapter = get_chapter($snippet, $terms);
    print("Chapter is: c".$chapter."\n");
	//print_r($chapter);

	//if ($chapter) {
	//    echo 'Chapter is: '. $chapter;
	//    
	//}
}




