【问题标题】:How to capture delimiter in different array or designated key with preg_split?如何使用 preg_split 捕获不同数组或指定键中的分隔符?
【发布时间】:2014-04-15 20:08:27
【问题描述】:

更新:第一个问题已解决,是 HTML/浏览器的问题。

第二个问题: 有没有办法将分隔符输出到单独的数组中?如果我使用 PREG_SPLIT_DELIM_CAPTURE,它将分隔符混合到同一个数组中并使其混淆,而不是 PREG_SPLIT_OFFSET_CAPTURE 指定它自己的偏移键。

代码:

$str = 'world=earth;world!=mars;world>venus';
$arr = preg_split('/([;|])/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);

echo "<pre>";
print_r($arr);
echo "</pre>";

DELIM CAPTURE 示例:

Array
(
    [0] => world=earth
    [1] => ;
    [2] => world!=mars
    [3] => ;
    [4] => world>venus
)

偏移捕获示例:

Array
(
    [0] => Array
        (
            [0] => world=earth
            [1] => 0
        )

    [1] => Array
        (
            [0] => world!=mars
            [1] => 12
        )

    [2] => Array
        (
            [0] => world>venus
            [1] => 34
        )

)

【问题讨论】:

  • 在 HTML 上下文中使用 htmlspecialchars 输出包含尖括号的内容。其他查看源代码。
  • 是的,你是对的。好吧,这很愚蠢,我使用的是在线 PHP 编辑器,看起来即使没有 pre,由于浏览器,输出也会被阻止。

标签: php regex preg-split


【解决方案1】:

从技术上讲,您不能这样做,但在这种特殊情况下,事后您可以很容易地做到这一点:

print_r(array_chunk($arr, 2));

输出:

Array
(
    [0] => Array
        (
            [0] => world=earth
            [1] => ;
        )

    [1] => Array
        (
            [0] => world!=mars
            [1] => ;
        )

    [2] => Array
        (
            [0] => world>venus
        )

)

另请参阅:array_chunk()

【讨论】:

    【解决方案2】:

    你不能!

    一种方法是使用preg_match_all而不是preg_split来获得你想要的:

    $pattern = '~[^;|]+(?=([;|])?)~';
    
    preg_match_all($pattern, $str, $arr, PREG_SET_ORDER);
    

    这个想法是将一个可选的捕获组放在捕获分隔符的前瞻中。

    如果你想确保不同的结果是连续的,你必须在模式中添加这个检查:

    $pattern = '~\G[;|]?\K[^;|]+(?=([;|])?)~';
    

    图案细节:

    \G           # the end of the last match position ( \A at the begining )
    [;|]?        # optional delimiter (the first item doesn't have a delimiter)
    \K           # reset all that has been matched before from match result
    [^;|]+       # all that is not the delimiter
    (?=          # lookead: means "followed by"
        ([;|])?  # capturing group 1 (optional): to capture the delimiter 
    )            # close the lookahead
    

    【讨论】:

      【解决方案3】:

      这是我在运行 PHP 代码时从 Chrome 浏览器得到的结果:

      <pre>Array
      (
          [0] =&gt; world=earth
          [1] =&gt; world!=mars
          [2] =&gt; world<sun [3]=""> world&gt;venus
      )
      </sun></pre>
      

      所以preg_split 函数运行良好。只是 HTML 中数组转储的问题。

      【讨论】:

      • 是的,谢谢,是视图问题而不是代码问题。我已经编辑了这个问题。
      • @Devon 你速度超快 ;)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-27
      • 2022-10-17
      相关资源
      最近更新 更多