2

This is my string:

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

I want to get 'hello' and '123qwa' from string.

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'.

Example: 
$string="VARHELLO=H3Ll0VARWELCOME=W3l60m3";
7
  • Look at PHP's parse_str() function Commented Jul 21, 2015 at 13:45
  • why dont you split with a separator like "VARHELLO=H3Ll0&VARWELCOME=W3l60m3" then explode into an array? Commented Jul 21, 2015 at 13:46
  • Ok what If the separator is space? Commented Jul 21, 2015 at 13:46
  • @bub - the separator is the VAR part. Commented Jul 21, 2015 at 13:48
  • I already tried the separator '&' and used 'parse_str()', and it works but this is the given problem. Commented Jul 21, 2015 at 13:49

2 Answers 2

4

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)

<?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"
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. You save my time.
I would recommend against using parse_str() as it pollutes scope, and could introduce security issues: "VAR&_GET=..."
2

Jessica's answer is perfect, but if you want to get it using 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]

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.