【问题标题】:Is there way to keep delimiter while using php explode or other similar functions?有没有办法在使用 php explode 或其他类似功能时保留分隔符?
【发布时间】:2023-04-03 09:13:01
【问题描述】:

例如,我有一篇文章应该按照“.”、“?”、“!”和“:”等句子边界进行拆分。

但是众所周知,无论是preg_split 还是explode 函数,它们都去掉了分隔符。

任何帮助将不胜感激!

编辑:

我只能想出下面的代码,不过效果很好。

$content=preg_replace('/([\.\?\!\:])/',"\\1[D]",$content);

谢谢!!!每个人。得到3个答案只需五分钟!我必须为在提问之前无法仔细查看 PHP 手册而道歉。对不起。

【问题讨论】:

标签: php


【解决方案1】:

我觉得这值得添加。您可以通过使用regex lookahead 来将分隔符保留在“after”字符串中:

$input = "The address is http://stackoverflow.com/";
$parts = preg_split('@(?=http://)@', $input);
// $parts[1] is "http://stackoverflow.com/"

如果分隔符是固定长度的,你可以使用lookbehind将分隔符保留在“之前”部分:

$input = "The address is http://stackoverflow.com/";
$parts = preg_split('@(?<=http://)@', $input);
// $parts[0] is "The address is http://"

在大多数情况下,这种解决方案更简单、更干净。

【讨论】:

  • 您甚至可以像这样使用多个分隔符:preg_split('@(?=(http://|https://))@', $input)(保留在“之后”中)
【解决方案2】:

您可以在使用preg_split 时设置标志PREG_SPLIT_DELIM_CAPTURE 并捕获分隔符。然后您可以将每对 2‍n 和 2‍n+1 重新组合在一起:

$parts = preg_split('/([.?!:])/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
$sentences = [];
for ($i = 0, $n = count($parts) - 1; $i <= $n; $i += 2) {
    $sentences[] = $parts[$i] . ($parts[$i+1] ?? '');
}

注意将拆分分隔符打包成一个组,否则不会被捕获。

【讨论】:

  • 正是我想要做的......但我太懒了,无法输入:-)
【解决方案3】:

preg_split 带有PREG_SPLIT_DELIM_CAPTURE 标志

例如

$parts = preg_split("/([\.\?\!\:])/", $string, -1, PREG_SPLIT_DELIM_CAPTURE);

【讨论】:

    【解决方案4】:

    试试T-Regx

    <?php
    $parts = pattern('([.?!:])')->split($string);
    

    【讨论】:

      【解决方案5】:

      解析英语句子有很多细微差别和边缘情况。这使得制作一个完美的解析器变得非常困难。使用您的真实项目数据拥有足够的测试用例以确保您涵盖所有场景,这一点很重要。

      无需为此任务使用环视或捕获组。您只需匹配标点符号,然后用\K 忘记它们,然后匹配出现在句子之间的一个或多个空格字符。如果您的字符串以满足该模式的字符开头或结尾,则使用 PREG_SPLIT_NO_EMPTY 标志可防止创建空元素。

      代码:(Demo)

      $str = 'Heading: This is a string. Very exciting! What do you think? ...one more thing, this is cool.';
      
      var_export(
          preg_split('~[.?!:]+\K\s+~', $str, 0, PREG_SPLIT_NO_EMPTY)
      );
      

      输出:

      array (
        0 => 'Heading:',
        1 => 'This is a string.',
        2 => 'Very exciting!',
        3 => 'What do you think?',
        4 => '...one more thing, this is cool.',
      )
      

      【讨论】:

        猜你喜欢
        • 2015-02-12
        • 1970-01-01
        • 2021-07-06
        • 1970-01-01
        • 2019-12-18
        • 1970-01-01
        • 2010-12-22
        • 2022-11-29
        • 1970-01-01
        相关资源
        最近更新 更多