简体   繁体   English

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

[英]PHP: How to get specific word from string

This is my string: 这是我的字符串:

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

I want to get 'hello' and '123qwa' from string. 我想从字符串中获取“ hello”和“ 123qwa”。

My pseudo code is. 我的伪代码是。

if /^VARHELLO/ exist
    get hello(or whatever comes after VARHELLO and before VARWELCOME)
if /^VARWELCOME/ exist
    get 123qwa(or whatever comes after VARWELCOME)

Note : values from 'VARHELLO' and 'VARWELCOME' are dynamic, so 'VARHELLO' could be 'H3Ll0' or VARWELCOME could be 'W3l60m3'. 注意 :来自“ VARHELLO”和“ VARWELCOME”的值是动态的,因此“ VARHELLO”可以是“ H3Ll0”或VARWELCOME可以是“ W3l60m3”。

Example: 
$string="VARHELLO=H3Ll0VARWELCOME=W3l60m3";

Here is some code that will parse this string out for you into a more usable array. 这是一些代码,它将为您解析此字符串为更可用的数组。

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

Output: 输出:

array(2) {
  ["HELLO"]=>
  string(5) "hello"
  ["WELCOME"]=>
  string(6) "123qwa"
}

Or, an alternative using parse_str ( http://php.net/manual/en/function.parse-str.php ) 或者,使用parse_strhttp://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);

Output: 输出:

string(27) "&HELLO=hello&WELCOME=123qwa"
string(5) "hello"
string(6) "123qwa"

Jessica's answer is perfect, but if you want to get it using preg_match 杰西卡的答案很完美,但是如果您想使用preg_match获得答案

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

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

var_dump($m);

your results will be $m[1] and $m[2] 您的结果将是$m[1]$m[2]

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

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM