这是我的字符串:
$string="VARHELLO=helloVARWELCOME=123qwa";
我想从字符串中获取 'hello' 和 '123qwa'。
我的伪代码是。
if /^VARHELLO/ exist get hello(or whatever comes after VARHELLO and before VARWELCOME) if /^VARWELCOME/ exist get 123qwa(or whatever comes after VARWELCOME)
注意:“VARHELLO”和“VARWELCOME”的值是动态的,因此“VARHELLO”可能是“H3Ll0”或 VARWELCOME 可能是“W3l60m3”。
Example: $string="VARHELLO=H3Ll0VARWELCOME=W3l60m3";
最佳答案
这里有一些代码可以为您将这个字符串解析成一个更有用的数组。
<?php
$string="VARHELLO=helloVARWELCOME=123qwa";
$parsed = [];
$parts = explode('VAR', $string);
foreach($parts AS $part){
if(strlen($part)){
$subParts = explode('=', $part);
$parsed[$subParts[0]] = $subParts[1];
}
}
var_dump($parsed);
输出:
array(2) {
["HELLO"]=>
string(5) "hello"
["WELCOME"]=>
string(6) "123qwa"
}
或者,另一种方法是使用 parse_str
( http://php.net/manual/en/function.parse-str.php )
<?php
$string="VARHELLO=helloVARWELCOME=123qwa";
$string = str_replace('VAR', '&', $string);
var_dump($string);
parse_str($string);
var_dump($HELLO);
var_dump($WELCOME);
输出:
string(27) "&HELLO=hello&WELCOME=123qwa"
string(5) "hello"
string(6) "123qwa"
关于PHP:如何从字符串中获取特定单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31540855/