Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/249.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP:如何从字符串中获取特定单词_Php_Arrays_String - Fatal编程技术网

PHP:如何从字符串中获取特定单词

PHP:如何从字符串中获取特定单词,php,arrays,string,Php,Arrays,String,这是我的字符串:$string=“VARHELLO=helloVARWELCOME=123qwa” $string="VARHELLO=helloVARWELCOME=123qwa"; 我想从字符串中获取“hello”和“123qwa” 我的伪代码是 if /^VARHELLO/ exist get hello(or whatever comes after VARHELLO and before VARWELCOME) if /^VARWELCOME/ exist get 12

这是我的字符串:$string=“VARHELLO=helloVARWELCOME=123qwa”

$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/存在 获取hello(或VARHELLO之后和VARWELCOME之前的任何内容) 如果/^VARWELCOME/存在 获得123qwa(或VARWELCOME之后的任何内容) 注意:来自“VARHELLO”和“VARWELCOME”的值是动态的,因此“VARHELLO”可以是“H3Ll0”或“VARWELCOME”可以是“W3l60m3”

Example: $string="VARHELLO=H3Ll0VARWELCOME=W3l60m3"; 例子:
$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);
或者,使用
parse_str
()


Jessica的答案很完美,但是如果你想使用
preg\u match

$string="VARHELLO=helloVARWELCOME=123qwa";

preg_match('/VARHELLO=(.*?)VARWELCOME=(.*)/is', $string, $m);

var_dump($m);
您的结果将是
$m[1]
$m[2]

array(3) {
  [0]=>
    string(31) "VARHELLO=helloVARWELCOME=123qwa"
  [1]=>
    string(5) "hello"
  [2]=>
    string(6) "123qwa"

}

看看PHP的函数,为什么不使用“VARHELLO=H3Ll0&VARWELCOME=W3l60m3”这样的分隔符拆分,然后分解成一个数组?好吧,如果分隔符是空格呢?@bub-分隔符就是VAR部分。我已经尝试了分隔符“&”并使用了“parse_str()”,它可以工作,但这是给定的问题。谢谢。您节省了我的时间。我建议不要使用parse_str(),因为它会污染作用域,并可能引入安全问题:
“VAR&\u GET=…”
string(27) "&HELLO=hello&WELCOME=123qwa"
string(5) "hello"
string(6) "123qwa"
$string="VARHELLO=helloVARWELCOME=123qwa";

preg_match('/VARHELLO=(.*?)VARWELCOME=(.*)/is', $string, $m);

var_dump($m);
array(3) {
  [0]=>
    string(31) "VARHELLO=helloVARWELCOME=123qwa"
  [1]=>
    string(5) "hello"
  [2]=>
    string(6) "123qwa"