【问题标题】:preg_split using PREG_SPLIT_DELIM_CAPTURE with an array of delimspreg_split 使用带有分隔符数组的 PREG_SPLIT_DELIM_CAPTURE
【发布时间】:2013-04-30 16:03:20
【问题描述】:

注意:我最近问过这个问题,但事实证明我正在寻找的解决方案比我最初想象的要先进。

使用 preg_split,我将如何拆分它,注意分隔符之前的字符串会有所不同:

$string = "big red apple one purple grape some stuff then green apple yatta yatta red cherry green gape";

我想使用一个字符串数组作为分隔符,我希望它们包含在结果中。分隔符:[苹果、葡萄、樱桃]

我想要的输出是:

Array("big red apple", "one purple grape", "some stuff then green apple", "yatta yatta red cherry", "green grape");

这是我最初的:

$string = "big red apple one purple grape some stuff then green apple yatta yatta red cherry green gape";
$matches = preg_split('(apple|grape|cherry)', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r($matches);

它打印这个: 数组([0] => 大红色 [1] => 一个紫色 [2] => 一些东西,然后是绿色 [3] => yatta yatta red [4] => green gape)

没有分隔符。

【问题讨论】:

标签: php arrays preg-split


【解决方案1】:

如果您修正了输入字符串中最后一个单词的拼写错误,那么(一种可能的)模式是:

~(?<=apple|grape|cherry)\s*~

这是使用a look-behind,然后在下面的空白处拆分(如果存在)。所以它也适用于字符串的末尾。

完整示例:

<?php
/**
 * preg_split using PREG_SPLIT_DELIM_CAPTURE with an array of delims
 * @link http://stackoverflow.com/a/16304338/2261774
 */

$string = "big red apple one purple grape some stuff then green apple yatta yatta red cherry green grape";

var_dump(
    preg_split("~(?<=apple|grape|cherry)\s*~", $string, -1, PREG_SPLIT_NO_EMPTY)
);

See it in action.

如您所见,我在这里没有使用PREG_SPLIT_DELIM_CAPTURE,因为我想删除我拆分的空格。而是使用PREG_SPLIT_NO_EMPTY 标志,这样我就不会在字符串末尾得到(空)拆分。

【讨论】:

    【解决方案2】:

    简单一点,结果一样:

    $string = "big red apple one purple grape some stuff then green apple yatta yatta red cherry green grape";
    $re='/\S.*?\s(?:apple|grape|cherry)/';
    preg_match_all($re,$string,$m);
    var_dump($m[0]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多