PHP preg_split具有两个定界符,并且仅捕获一个 [英] PHP preg_split with two delimiters and capture only one

查看:76
本文介绍了PHP preg_split具有两个定界符,并且仅捕获一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在正则表达式上确实很糟糕,在此先对不起!

Really poor at regular expressions, sorry in advance!

我尽了最大的努力弄清楚了如何将字符串分割成带有两个定界符的数组,并且仍然捕获一个并将其包含在最终数组中。 preg_split 似乎很理想,但是我的正则表达式让我失望了。

I've tried my best to work out how to split a string into a array with two delimiters and still capture one and include it in the final array. preg_split seems ideal for this but my regular expression is letting me down.

例如,如果我已经字符串 foo = bar AND bar = foo ;我想在一个空格或 = 字符处拆分字符串,但要保留 = 以便数组看起来像这样:

If for example, I've the string foo = bar AND bar=foo; I want to split the string at either a space, or the = character BUT keep the = so the array would look like:

Array
(
    [0] => foo
    [1] => =
    [2] => bar
    [3] => AND
    [4] => bar
    [5] => =
    [6] => foo
)

不幸的是,我得到了:

Array
(
    [0] => foo
    [1] => 
    [2] => =
    [3] => 
    [4] => bar
    [5] => AND
    [6] => bar
    [7] => =
    [8] => foo
)

我在这里获得此代码(在PHP中):

I've got here with this code (in PHP):

<!doctype html>
<?php

$string = 'foo = bar AND bar=foo';

$array = preg_split('/ +|(=)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);

?>
<pre>
<?php

print_r($array);

?>
</pre>

我真的很感谢你们能提供的任何帮助,谢谢大家!

I'd really appreciate any help you guys can give, thanks everyone!

推荐答案

添加 PREG_SPLIT_NO_EMPTY 标志:

$string = 'foo = bar AND bar=foo';
$array = preg_split('/ +|(=)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

现在,这输出

Array
(
    [0] => foo
    [1] => =
    [2] => bar
    [3] => AND
    [4] => bar
    [5] => =
    [6] => foo
)

这篇关于PHP preg_split具有两个定界符,并且仅捕获一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆