确定不同类型文本中的章节号

Hen*_*son 21 php regex

我正在从小说相关帖子中提取标题.目的是通过使用正则表达式来确定帖子的章节.每个站点使用不同的方式来识别章节.以下是最常见的情况:

$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
Run Code Online (Sandbox Code Playgroud)

章节编号始终列在标题中,只是在上面显示的不同变体中.

到目前为止我有什么

到目前为止,我有一个正则表达式来确定章节的单个案例,例如:

$title = '9 text chapter 25.6 text'; // c25.6
Run Code Online (Sandbox Code Playgroud)

使用此代码(尝试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'];
}
Run Code Online (Sandbox Code Playgroud)

如何使用上面列出的其他示例进行此操作?考虑到这个问题的复杂性,我会在符合条件的情况下给予200点积分.

Wik*_*żew 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;
}
Run Code Online (Sandbox Code Playgroud)

请参阅PHP演示.

要点

  • 匹配cchapter/ chapters与跟随他们的数字,只捕获c和数字
  • 找到匹配项后,处理包含数字序列的组2
  • 所有<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'
Run Code Online (Sandbox Code Playgroud)

请参阅正则表达式演示.

图案细节

  • (?|(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字母,后跟非字母字符串或字符串结尾(注意不区分大小写的修饰符也会[A-Z]匹配小写ASCII信)
    • (?:\s*(?:[,&+-]|and)\s*(?:(?:e(?:pisodes?)|c(?:hapters?)|c(?:hs?)|e(?:ps?)|c(?:s?)|e(?:s?)|)\s*)?(?4))* - 零个或多个序列
      • \s*(?:[,&+-]|and)\s*-一个,,&,+,-and具有可选0+空格封闭
      • (?: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"
Run Code Online (Sandbox Code Playgroud)

用于preg_replace_callback删除之间的空格-(如果有的话)和术语(如果有的话)后跟0 +空格字符,如果组1匹配,则匹配被拆分

"~\s*(?:[,&+]|and)\s*(?:$chapter_aux_rx)?~ui"
Run Code Online (Sandbox Code Playgroud)

正则表达式(其匹配&,,,+and在之间的任意0+空格,随后用0+空格,然后可选字符串,术语随后与0+空格)和数组传递到buildNumChain该构建得到的字符串功能.

  • @HenrikPetterson是的,我有,但是我很困惑的是,当值为"0"时,我的捕获被评估为空.我将`!empty`改为`strlen ...> 0`,这似乎现在有用了.请参阅[此更新](https://ideone.com/gzaRA9)(我还更改了`$ x [2]`的处理,但我怀疑它是否至关重要). (2认同)

ElC*_*Net 8

我认为构建这样的东西是非常复杂的而不会产生一些误报因为某些模式可能包含在标题中,在这些情况下,它们将被代码检测到.

无论如何,我将展示一个可能对您有用的解决方案,并在您有时间时进行实验.我没有对它进行过深入的测试,所以,如果您发现此实现有任何问题,请告诉我,我会尝试找到解决方案.

看看你的模式,所有这些都可以分成两大组:

  • 从一个数字到另一个数字(G1)
  • 由逗号,加号或符号分隔的一个或多个数字(G2)

因此,如果我们可以将这两个群体分开,我们可以区别对待它们.从下一个标题中,我将尝试以这种方式获取章节编号:

+-------------------------------------------+-------+------------------------+
| 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                 | 
+-------------------------------------------+-------+------------------------+
Run Code Online (Sandbox Code Playgroud)

为了只提取章节的数量并区分它们,一种解决方案可以是构建一个正则表达式,它捕获章节范围(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;
    }

}
Run Code Online (Sandbox Code Playgroud)

您可以查看在Ideone上运行的代码.


Jul*_*lio 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";
}
Run Code Online (Sandbox Code Playgroud)

输出:请参阅:https://ideone.com/Ebzr9R

  • @HenrikPetterson我添加了'005'和'5.00'数字清理 (2认同)