0

Since I don't like using a regex I would like to ask if there's another easy way to extract values from a string.

Example strings:

send 0.2 XYZ ABC DEF

In the example above I would need to extract all values meaning I would need:

$string_1 = "send";
$string_2 = "0.2";
$string_3 = "XYZ";
$string_4 = "ABC";
$string_5 = "DEF";

Is there some way easy way to filter the above example? The " separating symbol" would be always a " " (blank space).

john_doee
  • 45
  • 1
  • 8
  • http://php.net/manual/en/function.str-split.php or http://php.net/manual/en/function.explode.php I think would work. You need them as variables or an array would work? – user3783243 Jun 18 '18 at 17:00
  • 1
    Possible duplicate of [Splitting up a string in PHP with every blank space](https://stackoverflow.com/questions/5020202/splitting-up-a-string-in-php-with-every-blank-space) – user3783243 Jun 18 '18 at 17:02
  • Never use a variable pattern of 1,2,3,4,5 etc. Just use an array... – Devon Bessemer Jun 18 '18 at 17:05

1 Answers1

2

You can do it without any regex but using simple php function like list() and explode(). Try like this way.

<?php
$string = 'send 0.2 XYZ ABC DEF';
list($string_1, $string_2, $string_3, $string_4, $string_5) = explode(' ', $string);
echo $string_1. PHP_EOL;
echo $string_2. PHP_EOL;
echo $string_3. PHP_EOL;
echo $string_4. PHP_EOL;
echo $string_5. PHP_EOL;
?>

Program Output:

send
0.2
XYZ
ABC
DEF

SEE DEMO: https://eval.in/1022829

Edit: With for() loop,

$length = count($array);
for ($i = 0; $i < $length; $i++) {
    $name = "string_".($i+1);
    $$name = $array[$i];
}
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103