是否可以使用这样的字符串:
|
details==Here are some details
|
facebook_url==therweerw
|
random_word==blah blah
|
得到这个:
$details = "Here are some details";
$facebook_url = "therweerw";
$random_word = "blah blah";
重点是我想以一种方式解析它,“==”分隔符左边的字符串将成为一个变量,右边的字符串就是它的字符串。我不想对这些变量进行硬编码。
答案 0 :(得分:5)
$str = '|
details==Here are some details
|
facebook_url==therweerw
|
random_word==blah blah
|';
preg_match_all('~^(\w+)==(.*)$~m', $str, $matches);
foreach ($matches[1] as $i => $name) {
$$name = $matches[2][$i];
}
var_dump($details, $facebook_url, $random_word);
并运行示例:http://ideone.com/Vns7Y
答案 1 :(得分:1)
您可以使用explode()
加extract()
的组合来执行此操作。
答案 2 :(得分:1)
我可能会使用preg_match_all()
,但这是explode()
的示例:
$str = "|
details==Here are some details
|
facebook_url==therweerw
|
random_word==blah blah
|";
$str = str_replace("\r", '', $str);
$str = trim($str, "|\r\n");
foreach ( explode("\n|\n", $str) as $line ) {
$line = trim($line);
list($varName, $varValue) = explode('==', $line);
${$varName} = $varValue;
}
var_dump($details, $facebook_url, $random_word);
输出:
string 'Here are some details' (length=21)
string 'therweerw' (length=9)
string 'blah blah' (length=9)