在引号内包含定界符

在引号内包含定界符

本文介绍了PHP preg_split具有两个定界符,除非在引号内包含定界符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我之前关于得益于nick,它的响应速度非常快。我真的很想扩展该方案,以在引号内包含定界符时不拆分字符串。例如:

Further on from my previous question about preg_split which was answers super fast, thanks to nick; I would really like to extend the scenario to no split the string when a delimiter is within quotes. For example:

如果我有字符串 foo = bar AND bar = foo或foobar = foo bar ,我希望在每个空格或 = 字符上拆分字符串,但在返回的数组中包含 = 字符(当前效果很好),但是我不想拆分字符串中的两个分隔符都放在引号内。

If I have the string foo = bar AND bar=foo OR foobar="foo bar", I'd wish to split the sting on every space or = character but include the = character in the returned array (which works great currently), but I don't want to split the string either of the delimiters are within quotes.

到目前为止,我已经知道了:

I've got this so far:

<!doctype html>
<?php

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

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

?>
<pre>
<?php

print_r($array);

?>
</pre>

哪个会吸引我:

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

但是如果我将字符串更改为:

But if I changed the string to:

$string = 'foo = bar AND bar=foo OR foobar = "foo bar"';

我真的希望数组为:

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

注意 foo bar 没有拆分

真的不确定如何在RegEx内执行此操作,或者是否有更好的方法,但是您的所有帮助将不胜感激!

Really not sure how to do this within the RegEx or if there is even a better way but all your help would be very much appreciated!

谢谢大家!

推荐答案

我能够通过添加带引号的字符串作为分隔符a-la来做到这一点

I was able to do this by adding quoted strings as a delimiter a-la

"(.*?)"| +|(=)

引用的部分将被捕获。看来这有点脆弱,我没有对其进行广泛的测试,但这至少可以在您的示例中使用。

The quoted part will be captured. It seems like this is a bit tenuous and I did not test it extensively, but it at least works on your example.

这篇关于PHP preg_split具有两个定界符,除非在引号内包含定界符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 01:07