0

I get string:

$res = "RESULT: SUCCESS
NUMBER_TYPE:    0";

I want get "RESULT" and for this i use explode:

$arr = explode('\n\r', $res);
$result = trim(explode('RESULT:', $arr[0]));

But i get Arrayfalse

Tell me please how correctly get RESULT?

P.S.: result should been SUCCESS

4
  • 2
    if (preg_match('/RESULT:\s*(\w+)/', $res, $match)) echo $match[1]; - regular-expressions.info Commented Jan 31, 2014 at 8:47
  • @deceze thanks but need with explode Commented Jan 31, 2014 at 8:48
  • 1
    Just saying that sometimes there are better tools... :) Commented Jan 31, 2014 at 8:48
  • 1
    Any reason why you need explode? It really is not the right method for this parsing job. Commented Jan 31, 2014 at 9:07

4 Answers 4

1

You can use explode then preg_split

$arr = explode(':', $res);
$arr = preg_split('/\s+/', $arr[1]);
echo $arr[1];

You can also use this one with explode only.

$arr = explode("\n", $res);
$arr= explode(":", $arr[0]);
echo trim($arr[1]);
Sign up to request clarification or add additional context in comments.

Comments

0

Trying Doing this

$arr = explode(':', $res);
$result = explode(' ', $arr[1]);
print_r($result[0]);

Comments

0

Try :

$ex = explode(":",$res);
$result = explode("\n",$ex[1]);
$result = $result[0];
echo trim($result); //echoes SUCCESS

Or :

$ex = explode("\n", $res);
$result = explode(":", $ex[0]);
$result = $result[1];
echo trim($result); //echoes SUCCESS

Demo 1

Demo 2

9 Comments

It will show SUCCESS NUMBER_TYPE not SUCCESS ...which the OP doesnt want.
'\n' is "\n", not a line break.
@deceze I didn't understood you
@AlirezaFallah, Did you try the code yourself before posting this as answer ?
@AlirezaFallah in result with your answer will be ` SUCCESS NUMBER_TYPE` with line break after SUCCESS. try you code please.
|
0

The first comment to your answer is the solution. But - for any reason - if you want to get all the keys and values, you can use preg_match for each line. A quick example:

<?php

$res = "RESULT: SUCCESS
NUMBER_TYPE:    0";

$arr = explode("\n", $res);

foreach($arr as $line)
{
    if(preg_match('/^([A-Z_]+):\s+?([a-zA-Z0-9_]+)$/', $line, $matches))
    {
        echo "Key: " . $matches[1] . " - Value: " . $matches[2] . "\n";
    }
}

Output:

Key: RESULT - Value: SUCCESS
Key: NUMBER_TYPE - Value: 0

Comments

Your Answer

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