开发者

using explode() to split strings and set variables possible?

Is it possible to have a string like this:

|
details==Here are some details
|
facebook_url开发者_JAVA技巧==therweerw
|
random_word==blah blah
|

and get this:

$details = "Here are some details";
$facebook_url = "therweerw";
$random_word = "blah blah";

The main point is I'd like to parse this in a way that the string to the left of the "==" delimiter will become a variable with the string to the right as it's string. I'd like to not have to hard-code those variables.


$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);

And running sample: http://ideone.com/Vns7Y


You can use a combination of explode() plus extract() to do this.


I would probably use preg_match_all() for this, but here's example with 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);

Output:

string 'Here are some details' (length=21)
string 'therweerw' (length=9)
string 'blah blah' (length=9)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜