我正在从小说相关的帖子中获取标题。目的是通过使用正则表达式来确定帖子所涉及的章节。每个站点使用不同的方式来标识章节。以下是最常见的情况:
$title = 'text chapter 25.6 text'; // c25.6
$title = 'text chapters 23, 24, 25 text'; // c23-25
$title = 'text chapters 23+24+25 text'; // c23-25
$title = 'text chapter 23, 25 text'; // c23 & 25
$title = 'text chapter 23 & 24 & 25 text'; // c23-25
$title = 'text c25.5-30 text'; // c25.5-30
$title = 'text c99-c102 text'; // c99-102
$title = 'text chapter 99 - chapter 102 text'; // c99-102
$title = 'text chapter 1 - 3 text'; // c1-3
$title = '33 text chapter 1, 2 text 3'; // c1-2
$title = 'text v2c5-10 text'; // c5-10
$title = 'text chapters 23, 24, 25, 29, 31, 32 text'; // c23-25 & 29 & 31-32
章节编号始终列在标题中,只是上面显示的变化形式不同。
到目前为止,我有一个正则表达式来确定章节的单个情况,例如:
$title = '9 text chapter 25.6 text'; // c25.6
使用此代码(尝试ideone):
function get_chapter($text, $terms) {
if (empty($text)) return;
if (empty($terms) || !is_array($terms)) return;
$values = false;
$terms_quoted = array();
foreach ($terms as $term)
$terms_quoted[] = preg_quote($term, '/');
// search for matches in $text
// matches with lowercase, and ignores white spaces...
if (preg_match('/('.implode('|', $terms_quoted).')\s*(\d+(\.\d+)?)/i', $text, $matches)) {
if (!empty($matches[2]) && is_numeric($matches[2])) {
$values = array(
'term' => $matches[1],
'value' => $matches[2]
);
}
}
return $values;
}
$text = '9 text chapter 25.6 text'; // c25.6
$terms = array('chapter', 'chapters');
$chapter = get_chapter($text, $terms);
print_r($chapter);
if ($chapter) {
echo 'Chapter is: c'. $chapter['value'];
}
如何与上面列出的其他示例一起使用?鉴于这个问题的复杂性,我将在有资格的情况下悬赏200分。
答案 0 :(得分:13)
我建议以下方法结合正则表达式和常见的字符串处理逻辑:
preg_match
和相应的正则表达式来匹配整个文本块的第一个匹配项,从$terms
数组中的关键字开始,直到与该词相关的最后一个数字(+可选的部分字母) +
,&
或,
字符连接的情况下重建数字范围。这需要多步操作:1)在先前的总体匹配中匹配用连字符分隔的子字符串,并修剪掉不必要的零和空格,2)将数字块拆分为单独的项目,并将它们传递给一个单独的函数,该函数将生成数字范围
buildNumChain($arr)
函数将创建数字范围,如果字母跟随数字,则将其转换为后缀section X
。您可以使用
$strs = ['c0', 'c0-3', 'c0+3', 'c0 & 9', 'c0001, 2, 03', 'c01-03', 'c1.0 - 2.0', 'chapter 2A Hello', 'chapter 2AHello', 'chapter 10.4c', 'chapter 2B', 'episode 23.000 & 00024', 'episode 23 & 24', 'e23 & 24', 'text c25.6 text', '001 & 2 & 5 & 8-20 & 100 text chapter 25.6 text 98', 'hello 23 & 24', 'ep 1 - 2', 'chapter 1 - chapter 2', 'text chapter 25.6 text', 'text chapters 23, 24, 25 text','text chapter 23, 25 text', 'text chapter 23 & 24 & 25 text','text c25.5-30 text', 'text c99-c102 text', 'text chapter 1 - 3 text', '33 text chapter 1, 2 text 3','text chapters 23, 24, 25, 29, 31, 32 text', 'c19 & c20', 'chapter 25.6 & chapter 29', 'chapter 25+c26', 'chapter 25 + 26 + 27'];
$terms = ['episode', 'chapter', 'ch', 'ep', 'c', 'e', ''];
usort($terms, function($a, $b) {
return strlen($b) - strlen($a);
});
$chapter_main_rx = "\b(?|" . implode("|", array_map(function ($term) {
return strlen($term) > 0 ? "(" . substr($term, 0, 1) . ")(" . substr($term, 1) . "s?)": "()()" ;},
$terms)) . ")\s*";
$chapter_aux_rx = "\b(?:" . implode("|", array_map(function ($term) {
return strlen($term) > 0 ? substr($term, 0, 1) . "(?:" . substr($term, 1) . "s?)": "" ;},
$terms)) . ")\s*";
$reg = "~$chapter_main_rx((\d+(?:\.\d+)?(?:[A-Z]\b)?)(?:\s*(?:[,&+-]|and)\s*(?:$chapter_aux_rx)?(?4))*)~ui";
foreach ($strs as $s) {
if (preg_match($reg, $s, $m)) {
$p3 = preg_replace_callback(
"~(\d*(?:\.\d+)?)([A-Z]?)\s*-\s*(?:$chapter_aux_rx)?|(\d+(?:\.\d+)?(?:[A-Z]\b)?)(?:\s*(?:[,&+]|and)\s*(?:$chapter_aux_rx)?(?1))*~ui", function($x) use ($chapter_aux_rx) {
return (isset($x[3]) && strlen($x[3])) ? buildNumChain(preg_split("~\s*(?:[,&+]|and)\s*(?:$chapter_aux_rx)?~ui", $x[0]))
: ((isset($x[1]) && strlen($x[1])) ? ($x[1] + 0) : "") . ((isset($x[2]) && strlen($x[2])) ? ord(strtolower($x[2])) - 96 : "") . "-";
}, $m[3]);
print_r(["original" => $s, "found_match" => trim($m[0]), "converted" => $m[1] . $p3]);
echo "\n";
} else {
echo "No match for '$s'!\n";
}
}
function buildNumChain($arr) {
$ret = "";
$rngnum = "";
for ($i=0; $i < count($arr); $i++) {
$val = $arr[$i];
$part = "";
if (preg_match('~^(\d+(?:\.\d+)?)([A-Z]?)$~i', $val, $ms)) {
$val = $ms[1];
if (!empty($ms[2])) {
$part = ' part ' . (ord(strtolower($ms[2])) - 96);
}
}
$val = $val + 0;
if (($i < count($arr) - 1) && $val == ($arr[$i+1] + 0) - 1) {
if (empty($rngnum)) {
$ret .= ($i == 0 ? "" : " & ") . $val;
}
$rngnum = $val;
} else if (!empty($rngnum) || $i == count($arr)) {
$ret .= '-' . $val;
$rngnum = "";
} else {
$ret .= ($i == 0 ? "" : " & ") . $val . $part;
}
}
return $ret;
}
请参见PHP demo。
c
或chapter
/ chapters
与后面的数字匹配,仅捕获c
和数字<number>-c?<number>
子字符串应在数字和c
去除
,
/ &
分隔的数字都应使用buildNumChain
后处理,以产生连续数字之外的范围(假定为整数)。如果$terms = ['episode', 'chapter', 'ch', 'ep', 'c', 'e', '']
,主正则表达式将看起来像:
'~(?|(e)(pisodes?)|(c)(hapters?)|(c)(hs?)|(e)(ps?)|(c)(s?)|(e)(s?)|()())\s*((\d+(?:\.\d+)?(?:[A-Z]\b)?)(?:\s*(?:[,&+-]|and)\s*(?:(?:e(?:pisodes?)|c(?:hapters?)|c(?:hs?)|e(?:ps?)|c(?:s?)|e(?:s?)|)\s*)?(?4))*)~ui'
请参见regex demo。
模式详细信息
(?|(e)(pisodes?)|(c)(hapters?)|(c)(hs?)|(e)(ps?)|(c)(s?)|(e)(s?)|()())
-一个分支重置组,它捕获搜索词的第一个字母,并将其余词捕获到必填组2中。如果有空词,则添加()()
确保组中的分支包含相同数量的组\s*
-超过0个空格((\d+(?:\.\d+)?(?:[A-Z]\b)?)(?:\s*(?:[,&+-]|and)\s*c?(?3))*)
-第2组:
(\d+(?:\.\d+)?(?:[A-Z]\b)?)
-第3组:1+位数字,后跟.
,1+位数字的可选序列,然后是可选ASCII字母,后跟非单词char或结尾字符串(请注意,不区分大小写的修饰符将使[A-Z]
也与小写ASCII字母匹配)(?:\s*(?:[,&+-]|and)\s*(?:(?:e(?:pisodes?)|c(?:hapters?)|c(?:hs?)|e(?:ps?)|c(?:s?)|e(?:s?)|)\s*)?(?4))*
-零个或多个序列
\s*(?:[,&+-]|and)\s*
-包含{0}空格的,
,&
,+
,-
或and
(?:e(?:pisodes?)|c(?:hapters?)|c(?:hs?)|e(?:ps?)|c(?:s?)|e(?:s?)|)
-具有添加的可选复数结尾s
(?4)
-第4组模式重复发生/重复当正则表达式匹配时,组1的值为c
,因此它将是结果的第一部分。然后,
"~(\d*(?:\.\d+)?)([A-Z]?)\s*-\s*(?:$chapter_aux_rx)?|(\d+(?:\.\d+)?(?:[A-Z]\b)?)(?:\s*(?:[,&+]|and)\s*(?:$chapter_aux_rx)?(?1))*~ui"
在preg_replace_callback
内使用删除-
(如果有)和术语(如果有)之间的空格,后跟0+个空格字符,如果第1组匹配,则用< / p>
"~\s*(?:[,&+]|and)\s*(?:$chapter_aux_rx)?~ui"
regex(它与&
,,
,+
或and
匹配,在可选的0+空格后跟0+空格,然后是可选的字符串,后跟术语0+空格),并将数组传递到buildNumChain
函数,该函数生成结果字符串。
答案 1 :(得分:8)
我认为构建这样的内容而不抛出任何误报是非常复杂的,因为某些模式可能包含在标题中,在某些情况下,代码会检测到它们。
无论如何,我将向您介绍一种您可能会感兴趣的解决方案,请在有空的时候尝试一下。我尚未对其进行深入测试,因此,如果您发现此实现存在任何问题,请告诉我,我将尝试找到解决方案。
看看您的模式,它们都可以分为两大类:
因此,如果我们可以将这两个组分开,则可以将它们区别对待。在接下来的标题中,我将尝试以这种方式获取章节编号:
+-------------------------------------------+-------+------------------------+
| TITLE | GROUP | EXTRACT |
+-------------------------------------------+-------+------------------------+
| text chapter 25.6 text | G2 | 25.6 |
| text chapters 23, 24, 25 text | G2 | 23, 24, 25 |
| text chapters 23+24+25 text | G2 | 23, 24, 25 |
| text chapter 23, 25 text | G2 | 23, 25 |
| text chapter 23 & 24 & 25 text | G2 | 23, 24, 25 |
| text c25.5-30 text | G1 | 25.5 - 30 |
| text c99-c102 text | G1 | 99 - 102 |
| text chapter 99 - chapter 102 text | G1 | 99 - 102 |
| text chapter 1 - 3 text | G1 | 1 - 3 |
| 33 text chapter 1, 2 text 3 | G2 | 1, 2 |
| text v2c5-10 text | G1 | 5 - 10 |
| text chapters 23, 24, 25, 29, 31, 32 text | G2 | 23, 24, 25, 29, 31, 32 |
| text chapters 23 and 24 and 25 text | G2 | 23, 24, 25 |
| text chapters 23 and chapter 30 text | G2 | 23, 30 |
+-------------------------------------------+-------+------------------------+
要仅提取章节编号并对其进行区分,一种解决方案是构建一个正则表达式,以捕获章节范围(G1)的两组和由字符分隔的数字(G2)的一组。提取章节编号后,我们可以处理结果以显示正确格式化的章节。
代码如下:
我看到您还在问题中未包含的注释中添加了更多案例。如果要添加新案例,只需创建一个新的匹配模式并将其添加到最终的正则表达式中即可。只需遵循两个匹配组的范围规则,以及一个单个匹配组的规则,以数字分隔字符。此外,还要考虑到最详细的模式应位于较少的模式之前。例如,
ccc N - ccc N
应该位于cc N - cc N
之前,而最后一个应该位于c N - c N
之前。
$model = ['chapters?', 'chap', 'c']; // different type of chapter names
$c = '(?:' . implode('|', $model) . ')'; // non-capturing group for chapter names
$n = '\d+\.?\d*'; // chapter number
$s = '(?:[\&\+,]|and)'; // non-capturing group of valid separators
$e = '[ $]'; // end of a match (a space or an end of a line)
// Different patterns to match each case
$g1 = "$c *($n) *\- *$c *($n)$e"; // match chapter number - chapter number in all its variants (G1)
$g2 = "$c *($n) *\- *($n)$e"; // match chapter number - number in all its variants (G1)
$g3 = "$c *((?:(?:$n) *$s *)+(?:$n))$e"; // match chapter numbers separated by something in all its variants (G2)
$g4 = "((?:$c *$n *$s *)+$c *$n)$e"; // match chapter number and chater number ... and chapter numberin all its variants (G2)
$g5 = "$c *($n)$e"; // match chapter number in all its variants (G2)
// Build a big non-capturing group with all the patterns
$reg = "/(?:$g1|$g2|$g3|$g4|$g5)/";
// Function to process each title
function getChapters ($title) {
global $n, $reg;
// Store the matches in one flatten array
// arrays with three indexes correspond to G1
// arrays with two indexes correspond to G2
if (!preg_match($reg, $title, $matches)) return '';
$numbers = array_values(array_filter($matches));
// Show the formatted chapters for G1
if (count($numbers) == 3) return "c{$numbers[1]}-{$numbers[2]}";
// Show the formatted chapters for G2
if(!preg_match_all("/$n/", $numbers[1], $nmatches, PREG_PATTERN_ORDER)) return '';
$m = $nmatches[0];
$t = count($m);
$str = "c{$m[0]}";
foreach($m as $i => $mn) {
if ($i == 0) continue;
if ($mn == $m[$i - 1] + 1) {
if (substr($str, -1) != '-') $str .= '-';
if ($i == $t - 1 || $mn != $m[$i + 1] - 1) $str .= $mn;
} else {
if ($i < $t) $str .= ' & ';
$str .= $mn;
}
return $str;
}
}
答案 2 :(得分:7)
尝试一下。似乎可以使用给定的示例以及更多示例:
<?php
$title[] = 'c005 - c009'; // c5-9
$title[] = 'c5.00 & c009'; // c5 & 9
$title[] = 'text c19 & c20 text'; //c19-20
$title[] = 'c19 & c20'; // c19-20
$title[] = 'text chapter 19 and chapter 25 text'; // c19 & 25
$title[] = 'text chapter 19 - chapter 23 and chapter 25 text'; // c19-23 & 25 (c19 for termless)
$title[] = 'text chapter 19 - chapter 23, chapter 25 text'; // c19-23 & 25 (c19 for termless)
$title[] = 'text chapter 23 text'; // c23
$title[] = 'text chapter 23, chapter 25-29 text'; // c23 & 25-29
$title[] = 'text chapters 23-26, 28, 29 + 30 + 32-39 text'; // c23-26 & c28-30 & c32-39
$title[] = 'text chapter 25.6 text'; // c25.6
$title[] = 'text chapters 23, 24, 25 text'; // c23-25
$title[] = 'text chapters 23+24+25 text'; // c23-25
$title[] = 'text chapter 23, 25 text'; // c23 & 25
$title[] = 'text chapter 23 & 24 & 25 text'; // c23-25
$title[] = 'text c25.5-30 text'; // c25.5-30
$title[] = 'text c99-c102 text'; // c99-102 (c99 for termless)
$title[] = 'text chapter 1 - 3 text'; // c1-3
$title[] = 'sometext 33 text chapter 1, 2 text 3'; // c1-2 or c33 if no terms
$title[] = 'text v2c5-10 text'; // c5-10 or c2 if no terms
$title[] = 'text cccc5-10 text'; // c5-10
$title[] = 'text chapters 23, 24, 25, 29, 31, 32 text'; // c23-25 & 29 & 31-32
$title[] = 'chapter 19 - chapter 23'; // c19-23 or c19 for termless
$title[] = 'chapter 12 part 2'; // c12
function get_chapter($text, $terms) {
$rterms = sprintf('(?:%s)', implode('|', $terms));
$and = '(?: [,&+]|\band\b )';
$isrange = "(?: \s*-\s* $rterms? \s*\d+ )";
$isdotnum = '(?:\.\d+)';
$the_regexp = "/(
$rterms \s* \d+ $isdotnum? $isrange?
( \s* $and \s* $rterms? \s* \d+ $isrange? )*
)/mix";
$result = array();
$result['orignal'] = $text;
if (preg_match($the_regexp, $text, $matches)) {
$result['found_match'] = $tmp = $matches[1];
$tmp = preg_replace("/$rterms\s*/i", '', $tmp);
$tmp = preg_replace('/\s*-\s*/', '-', $tmp);
$chapters = preg_split("/\s* $and \s*/ix", $tmp);
$chapters = array_map(function($x) {
return preg_replace('/\d\K\.0+/', '',
preg_replace('/(?|\b0+(\d)|-\K0+(\d))/', '\1', $x
));
}, $chapters);
$chapters = merge_chapters($chapters);
$result['converted'] = join_chapters($chapters);
}
else {
$result['found_match'] = '';
$result['converted'] = $text;
}
return $result;
}
function merge_chapters($chapters) {
$i = 0;
$begin = $end = -1;
$rtchapters = array();
foreach ($chapters as $chapter) {
// Fetch next chapter
$next = isset($chapters[$i+1]) ? $chapters[$i+1] : -1;
// If not set, set begin chapter
if ($begin == -1) {$begin = $chapter;}
if (preg_match('/-/', $chapter)) {
// It is a range, we reset begin/end and store the range
$begin = $end = -1;
array_push($rtchapters, $chapter);
}
else if ($chapter+1 == $next) {
// next is current + 1, update end
$end = $next;
}
else {
// store result (if no end, then store current chapter, else store the range
array_push($rtchapters, sprintf('%s', $end == -1 ? $chapter : "$begin-$end"));
$begin = $end = -1; // reset, since we stored results
}
$i++; // needed for $next
}
return $rtchapters;
}
function join_chapters($chapters) {
return 'c' . implode(' & ', $chapters) . "\n";
}
print "\nTERMS LEGEND:\n";
print "Case 1. = ['chapters', 'chapter', 'ch', 'c']\n";
print "Case 2. = []\n\n\n\n";
foreach ($title as $t) {
// If some patterns start by same letters, use longest first.
print "Original: $t\n";
print 'Case 1. = ';
$result = get_chapter($t, ['chapters', 'chapter', 'ch', 'c']);
print_r ($result);
print 'Case 2. = ';
$result = get_chapter($t, []);
print_r ($result);
print "--------------------------\n";
}
输出:请参见:https://ideone.com/Ebzr9R
答案 3 :(得分:4)
使用捕获章信息的常规正则表达式。
$ python
Python 2.7.10 (default, Oct 6 2017, 22:29:07)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> time.sleep(100000000)
^CTraceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyboardInterrupt
>>>
>>>
>>> time.sleep(100000001)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 22] Invalid argument
然后使用发现'~text\s+(?|chapters?\s+(\d+(?:\.\d+)?(?:\s*[-+,&]\s*\d+(?:\.\d+)?)*)|(?:v\d+)?((?:c\s*)?\d+(?:\.\d+)?(?:\s*[-]\s*(?:c\s*)?\d+(?:\.\d+)?)*)|(chapters?\s+\d+(?:\.\d+)?(?:\s*[-+,&]\s*chapter\s+\d+(?:\.\d+)?)*))\s+text~'
的干净组1替换为'~[^-.\d+,&\r\n]+~'
。
然后使用此发现''
清理干净并替换为逗号'~[+&]~'
Updae
下面的php代码包含一个用于合并各个章节序列的功能
到章节范围。
主正则表达式,可读版本
','
Php代码示例
http://sandbox.onlinephpfunctions.com/code/128cab887b2a586879e9735c56c35800b07adbb5
text
\s+
(?|
chapters?
\s+
( # (1 start)
\d+
(?: \. \d+ )?
(?:
\s* [-+,&] \s*
\d+
(?: \. \d+ )?
)*
) # (1 end)
|
(?: v \d+ )?
( # (1 start)
(?: c \s* )?
\d+
(?: \. \d+ )?
(?:
\s* [-] \s*
(?: c \s* )?
\d+
(?: \. \d+ )?
)*
) # (1 end)
|
( # (1 start)
chapters?
\s+
\d+
(?: \. \d+ )?
(?:
\s* [-+,&] \s*
chapter
\s+
\d+
(?: \. \d+ )?
)*
) # (1 end)
)
\s+
text
输出
$array = array(
'text chapter 25.6 text',
'text chapters 23, 24, 25 text',
'text chapters 23+24+25 text',
'text chapter 23, 25 text',
'text chapter 23 & 24 & 25 text',
'text c25.5-30 text',
'text c99-c102 text',
'text chapter 99 - chapter 102 text',
'text chapter 1 - 3 text',
'33 text chapter 1, 2 text 3',
'text v2c5-10 text',
'text chapters 23, 24, 25, 29, 31, 32 text');
foreach( $array as $input ){
if ( preg_match( '~text\s+(?|chapters?\s+(\d+(?:\.\d+)?(?:\s*[-+,&]\s*\d+(?:\.\d+)?)*)|(?:v\d+)?((?:c\s*)?\d+(?:\.\d+)?(?:\s*[-]\s*(?:c\s*)?\d+(?:\.\d+)?)*)|(chapters?\s+\d+(?:\.\d+)?(?:\s*[-+,&]\s*chapter\s+\d+(?:\.\d+)?)*))\s+text~',
$input, $groups ))
{
$chapters_verbose = $groups[1];
$cleaned = preg_replace( '~[^-.\d+,&\r\n]+~', '', $chapters_verbose );
$cleaned = preg_replace( '~[+&]~', ',', $cleaned );
$cleaned_and_condensed = CondnseChaptersToRanges( $cleaned );
echo "\$title = '" . $input . "'; // c$cleaned_and_condensed\n";
}
}
function CondnseChaptersToRanges( $cleaned_chapters )
{
///////////////////////////////////////
// Combine chapter ranges.
// Explode on comma's.
//
$parts = explode( ',', $cleaned_chapters );
$size = count( $parts );
$chapter_condensed = '';
for ( $i = 0; $i < $size; $i++ )
{
//echo "'$parts[$i]' ";
if ( preg_match( '~^\d+$~', $parts[$i] ) )
{
$first_num = (int) $parts[$i];
$last_num = (int) $parts[$i];
$j = $i + 1;
while ( $j < $size && preg_match( '~^\d+$~', $parts[$j] ) &&
(int) $parts[$j] == ($last_num + 1) )
{
$last_num = (int) $parts[$j];
$i = $j;
++$j ;
}
$chapter_condensed .= ",$first_num";
if ( $first_num != $last_num )
$chapter_condensed .= "-$last_num";
}
else
$chapter_condensed .= ",$parts[$i]";
}
$chapter_condensed = ltrim( $chapter_condensed, ',' );
return $chapter_condensed;
}
答案 4 :(得分:1)
我分支了您的示例,添加了一些内容,例如“章”并同时匹配“ c”和“章”,然后从字符串中提取所有匹配的表达式,提取单个数字,展平找到的所有范围,并返回一个格式化的字符串,就像您在每个注释中的注释一样:
因此,这里是链接:ideone
函数本身(稍微修改一下):
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");
}
输出结果:
Chapter is: c25.6
Chapter is: c25.6
Chapter is: c23-25
Chapter is: c23-25
Chapter is: c23 & 25
Chapter is: c23-25
Chapter is: c25.5-30
Chapter is: c99-102
Chapter is: c99-102
Chapter is: c1-3
Chapter is: c1-2
Chapter is: c5-10
Chapter is: c23-25 & 29 & 31-32