我需要将空格分隔字符串(如hey 'this is' some text )标记为数组['hey', 'this is', 'some', 'text'] (单引号字符是转义字符)。
到目前为止,我使用的是空格,但它没有包含必要的转义字符。
$tokens = preg_split('/[\ \n\,]+/', $whitespaceDelimitedString);正则表达式忍者,出来!!拜托,谢谢。
发布于 2014-01-23 21:21:05
您可以使用以下代码:
$s = "hey 'this is' some text";
$a = preg_split("/'([^']*)'\s*|\s+/", $s, 0, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
print_r($a);产出:
Array
(
[0] => hey
[1] => this is
[2] => some
[3] => text
)发布于 2014-01-23 21:27:31
这里有一个内置的PHP函数:str_getcsv() http://www.php.net/manual/en/function.str-getcsv.php
所以这个简单的代码:
<?php
$string = "hey 'this is' some text";
$output = str_getcsv ( $string, ' ', "'");
print_r($output);...will输出:
数组( =>嘿1 =>,这是2 =>,约3 =>文本)
https://stackoverflow.com/questions/21319326
复制相似问题