How can I explode the following string:
我如何引爆下面的字符串:
Lorem ipsum "dolor sit amet" consectetur "adipiscing elit" dolor
into
成
array("Lorem", "ipsum", "dolor sit amet", "consectetur", "adipiscing elit", "dolor")
So that the text in quotation is treated as a single word.
所以引文中的文字被当作一个词来处理。
Here's what I have for now:
下面是我现在要讲的:
$mytext = "Lorem ipsum %22dolor sit amet%22 consectetur %22adipiscing elit%22 dolor"
$noquotes = str_replace("%22", "", $mytext");
$newarray = explode(" ", $noquotes);
but my code divides each word into an array. How do I make words inside quotation marks treated as one word?
但是我的代码将每个单词都分割成一个数组。如何使引号内的单词成为一个单词?
5 个解决方案
#1
80
You could use a preg_match_all(...)
:
您可以使用preg_match_all(…):
$text = 'Lorem ipsum "dolor sit amet" consectetur "adipiscing \\"elit" dolor';
preg_match_all('/"(?:\\\\.|[^\\\\"])*"|\S+/', $text, $matches);
print_r($matches);
which will produce:
这将会产生:
Array
(
[0] => Array
(
[0] => Lorem
[1] => ipsum
[2] => "dolor sit amet"
[3] => consectetur
[4] => "adipiscing \"elit"
[5] => dolor
)
)
And as you can see, it also accounts for escaped quotes inside quoted strings.
正如你所看到的,它也解释了引号内的转义引号。
EDIT
编辑
A short explanation:
一个简短的解释:
" # match the character '"'
(?: # start non-capture group 1
\\ # match the character '\'
. # match any character except line breaks
| # OR
[^\\"] # match any character except '\' and '"'
)* # end non-capture group 1 and repeat it zero or more times
" # match the character '"'
| # OR
\S+ # match a non-whitespace character: [^\s] and repeat it one or more times
And in case of matching %22
instead of double quotes, you'd do:
如果匹配%22而不是双引号,你应该这样做:
preg_match_all('/%22(?:\\\\.|(?!%22).)*%22|\S+/', $text, $matches);
#2
65
This would have been much easier with str_getcsv()
.
使用str_getcsv()会容易得多。
$test = 'Lorem ipsum "dolor sit amet" consectetur "adipiscing elit" dolor';
var_dump(str_getcsv($test, ' '));
Gives you
给你
array(6) {
[0]=>
string(5) "Lorem"
[1]=>
string(5) "ipsum"
[2]=>
string(14) "dolor sit amet"
[3]=>
string(11) "consectetur"
[4]=>
string(15) "adipiscing elit"
[5]=>
string(5) "dolor"
}
#3
4
You can also try this multiple explode function
你也可以尝试这个多重爆炸函数
function multiexplode ($delimiters,$string)
{
$ready = str_replace($delimiters, $delimiters[0], $string);
$launch = explode($delimiters[0], $ready);
return $launch;
}
$text = "here is a sample: this text, and this will be exploded. this also | this one too :)";
$exploded = multiexplode(array(",",".","|",":"),$text);
print_r($exploded);
#4
1
In some situations the little known token_get_all()
might prove useful:
在某些情况下,鲜为人知的token_get_all()可能被证明是有用的:
$tokens = token_get_all("<?php $text ?>");
$separator = ' ';
$items = array();
$item = "";
$last = count($tokens) - 1;
foreach($tokens as $index => $token) {
if($index != 0 && $index != $last) {
if(count($token) == 3) {
if($token[0] == T_CONSTANT_ENCAPSED_STRING) {
$token = substr($token[1], 1, -1);
} else {
$token = $token[1];
}
}
if($token == $separator) {
$items[] = $item;
$item = "";
} else {
$item .= $token;
}
}
}
Results:
结果:
Array
(
[0] => Lorem
[1] => ipsum
[2] => dolor sit amet
[3] => consectetur
[4] => adipiscing elit
[5] => dolor
)
#5
1
I came here with a complex string splitting problem similar to this, but none of the answers here did exactly what I wanted - so I wrote my own.
我带着一个类似的复杂的弦分裂问题来到这里,但是这里没有一个答案能达到我想要的效果——所以我写了我自己的答案。
I am posting it here just in case it is helpful to someone else.
我把它贴在这里,以防对别人有帮助。
This is probably a very slow and inefficient way to do it - but it works for me.
这可能是一种非常缓慢而低效的方法,但它对我有效。
function explode_adv($openers, $closers, $togglers, $delimiters, $str)
{
$chars = str_split($str);
$parts = [];
$nextpart = "";
$toggle_states = array_fill_keys($togglers, false); // true = now inside, false = now outside
$depth = 0;
foreach($chars as $char)
{
if(in_array($char, $openers))
$depth++;
elseif(in_array($char, $closers))
$depth--;
elseif(in_array($char, $togglers))
{
if($toggle_states[$char])
$depth--; // we are inside a toggle block, leave it and decrease the depth
else
// we are outside a toggle block, enter it and increase the depth
$depth++;
// invert the toggle block state
$toggle_states[$char] = !$toggle_states[$char];
}
else
$nextpart .= $char;
if($depth < 0) $depth = 0;
if(in_array($char, $delimiters) &&
$depth == 0 &&
!in_array($char, $closers))
{
$parts[] = substr($nextpart, 0, -1);
$nextpart = "";
}
}
if(strlen($nextpart) > 0)
$parts[] = $nextpart;
return $parts;
}
Usage is as follows. explode_adv
takes 5 arguments:
使用如下。explode_adv接受5个参数:
- An array of characters that open a block - e.g.
[
,(
, etc. - 打开一个块的一组字符,例如,(,等等)。
- An array of characters that close a block - e.g.
]
,)
, etc. - 关闭块的一组字符,例如,],等等。
- An array of characters that toggle a block - e.g.
"
,'
, etc. - 用于切换块的字符数组——例如。“,”等。
- An array of characters that should cause a split into the next part.
- 一个字符数组,它将导致下一部分的分裂。
- The string to work on.
- 要处理的字符串。
This method probably has flaws - edits are welcome.
这种方法可能有缺陷——编辑是受欢迎的。
#1
80
You could use a preg_match_all(...)
:
您可以使用preg_match_all(…):
$text = 'Lorem ipsum "dolor sit amet" consectetur "adipiscing \\"elit" dolor';
preg_match_all('/"(?:\\\\.|[^\\\\"])*"|\S+/', $text, $matches);
print_r($matches);
which will produce:
这将会产生:
Array
(
[0] => Array
(
[0] => Lorem
[1] => ipsum
[2] => "dolor sit amet"
[3] => consectetur
[4] => "adipiscing \"elit"
[5] => dolor
)
)
And as you can see, it also accounts for escaped quotes inside quoted strings.
正如你所看到的,它也解释了引号内的转义引号。
EDIT
编辑
A short explanation:
一个简短的解释:
" # match the character '"'
(?: # start non-capture group 1
\\ # match the character '\'
. # match any character except line breaks
| # OR
[^\\"] # match any character except '\' and '"'
)* # end non-capture group 1 and repeat it zero or more times
" # match the character '"'
| # OR
\S+ # match a non-whitespace character: [^\s] and repeat it one or more times
And in case of matching %22
instead of double quotes, you'd do:
如果匹配%22而不是双引号,你应该这样做:
preg_match_all('/%22(?:\\\\.|(?!%22).)*%22|\S+/', $text, $matches);
#2
65
This would have been much easier with str_getcsv()
.
使用str_getcsv()会容易得多。
$test = 'Lorem ipsum "dolor sit amet" consectetur "adipiscing elit" dolor';
var_dump(str_getcsv($test, ' '));
Gives you
给你
array(6) {
[0]=>
string(5) "Lorem"
[1]=>
string(5) "ipsum"
[2]=>
string(14) "dolor sit amet"
[3]=>
string(11) "consectetur"
[4]=>
string(15) "adipiscing elit"
[5]=>
string(5) "dolor"
}
#3
4
You can also try this multiple explode function
你也可以尝试这个多重爆炸函数
function multiexplode ($delimiters,$string)
{
$ready = str_replace($delimiters, $delimiters[0], $string);
$launch = explode($delimiters[0], $ready);
return $launch;
}
$text = "here is a sample: this text, and this will be exploded. this also | this one too :)";
$exploded = multiexplode(array(",",".","|",":"),$text);
print_r($exploded);
#4
1
In some situations the little known token_get_all()
might prove useful:
在某些情况下,鲜为人知的token_get_all()可能被证明是有用的:
$tokens = token_get_all("<?php $text ?>");
$separator = ' ';
$items = array();
$item = "";
$last = count($tokens) - 1;
foreach($tokens as $index => $token) {
if($index != 0 && $index != $last) {
if(count($token) == 3) {
if($token[0] == T_CONSTANT_ENCAPSED_STRING) {
$token = substr($token[1], 1, -1);
} else {
$token = $token[1];
}
}
if($token == $separator) {
$items[] = $item;
$item = "";
} else {
$item .= $token;
}
}
}
Results:
结果:
Array
(
[0] => Lorem
[1] => ipsum
[2] => dolor sit amet
[3] => consectetur
[4] => adipiscing elit
[5] => dolor
)
#5
1
I came here with a complex string splitting problem similar to this, but none of the answers here did exactly what I wanted - so I wrote my own.
我带着一个类似的复杂的弦分裂问题来到这里,但是这里没有一个答案能达到我想要的效果——所以我写了我自己的答案。
I am posting it here just in case it is helpful to someone else.
我把它贴在这里,以防对别人有帮助。
This is probably a very slow and inefficient way to do it - but it works for me.
这可能是一种非常缓慢而低效的方法,但它对我有效。
function explode_adv($openers, $closers, $togglers, $delimiters, $str)
{
$chars = str_split($str);
$parts = [];
$nextpart = "";
$toggle_states = array_fill_keys($togglers, false); // true = now inside, false = now outside
$depth = 0;
foreach($chars as $char)
{
if(in_array($char, $openers))
$depth++;
elseif(in_array($char, $closers))
$depth--;
elseif(in_array($char, $togglers))
{
if($toggle_states[$char])
$depth--; // we are inside a toggle block, leave it and decrease the depth
else
// we are outside a toggle block, enter it and increase the depth
$depth++;
// invert the toggle block state
$toggle_states[$char] = !$toggle_states[$char];
}
else
$nextpart .= $char;
if($depth < 0) $depth = 0;
if(in_array($char, $delimiters) &&
$depth == 0 &&
!in_array($char, $closers))
{
$parts[] = substr($nextpart, 0, -1);
$nextpart = "";
}
}
if(strlen($nextpart) > 0)
$parts[] = $nextpart;
return $parts;
}
Usage is as follows. explode_adv
takes 5 arguments:
使用如下。explode_adv接受5个参数:
- An array of characters that open a block - e.g.
[
,(
, etc. - 打开一个块的一组字符,例如,(,等等)。
- An array of characters that close a block - e.g.
]
,)
, etc. - 关闭块的一组字符,例如,],等等。
- An array of characters that toggle a block - e.g.
"
,'
, etc. - 用于切换块的字符数组——例如。“,”等。
- An array of characters that should cause a split into the next part.
- 一个字符数组,它将导致下一部分的分裂。
- The string to work on.
- 要处理的字符串。
This method probably has flaws - edits are welcome.
这种方法可能有缺陷——编辑是受欢迎的。