我有这种绳子。
'"asdfasdf","123456", this is a message. OK'
我想要做的是根据第一个和第二个引用值声明变量,然后声明消息的其余部分,直到确定。 (注意:
''
里面的字符串长度不一致)
$First = "asdfasdf"
$Second = "123456"
$Message = "this is a message"
这可能吗? 有类似
" "$First","$Second", "$Message" OK "
之类的方法吗?
这是 CSV 文件吗? 似乎没有,但如果是的话,你应该检查一下 php 的 csv 函数,特别是 str_getcsv。
如果没有,您应该只按 、 或 " 或您认为最准确的任何组合进行爆炸,然后遍历每个数组项。
$string = '"asdfasdf","123456","this is a message. OK"';
$temp = explode('","',$string);
$array = array();
foreach($temp as $key=>$value){
//do stuff with $value and $key
}
您可以使用正则表达式,如下所示:
代码
$raw = '"asdfasdf","123456", this is a message. OK'; // this is your raw text
preg_match('/^"(?P<first>[^"]+)","(?P<second>[^"]+)",\s+(?P<message>.+?) OK/', $raw, $matches); // this looks for the pattern you defined and stores the matches in $matches
print_r($matches); // this just dumps out the array of matching substrings
输出
Array
(
[0] => "asdfasdf","123456", this is a message. OK
[first] => asdfasdf
[1] => asdfasdf
[second] => 123456
[2] => 123456
[message] => this is a message.
[3] => this is a message.
)
您可以访问各个子字符串,例如
$matches['first']
、$matches['second']
或 $matches['message']
。
按照 PHP 上帝的意图,使用
str_getcsv()
解析完全有效的 CSV 字符串,然后使用对称数组解构为变量赋值。
代码:(演示)
[$first, $second, $message] = str_getcsv('"asdfasdf","123456", this is a message. OK');
var_dump($first, $second, $message);
输出:
string(8) "asdfasdf"
string(6) "123456"
string(22) " this is a message. OK"