PHP question - How to create an array from a string?

In my database, some field parameters are serialized and saved. When I do this:

print_r(unserialized($r['settings']));

I will get this:

Array ( 
[prefix] => 
[suffix] => 
[min] => 
[max] => 
[allowed_values] => 1|Common 2|Rare 3|Almost Extinct 
)

I am trying to create an array based on values ​​for allowed_values, such as:

Array (
[1] => Common
[2] => Rare
[3] => Almost Extinct
)

The problem is that when I use explode ("|", $ r ['allowed_values']), I get:

Array(
[0] => 1
[1] => Common 2
[2] => Rare 3
[3] => Almost Extinct
)

That makes sense, but obviously not what I was hoping for ... So, I'm just wondering if there is an easy way to do what I'm trying here? I thought about using the gap several times, once for spaces and once for pipes, but this will not work because of the space in "Almost Extinct" ...

+3
source share
4 answers

try the following:

 $tab=array();
 preg_match_all("/\s*(\d+)\|([^\d]+)/",$r['allowed_values'],$tab);
 print_r(array_combine($tab[1],$tab[2]));

:)

+3

1, , , . dweeves, .

$string = unserialized($r['settings']['allowed_values']);
//$string = '1|Common 2|Rare 3|Almost Extinct';

print_r (preg_split("/\d+\|/", $string, -1, PREG_SPLIT_NO_EMPTY));

:

Array
(
    [0] => Common 
    [1] => Rare 
    [2] => Almost Extinct
)
+2

, . "|" char

<?php
$string = "1|Faruk 2|Test";
$array = preg_split('/\d/', $string, -1, PREG_SPLIT_NO_EMPTY); 
$content = explode("|", implode($array));

var_dump($content);
?>

array(3) {
  [0]=>
  string(0) ""
  [1]=>
  string(6) "Faruk "
  [2]=>
  string(4) "Test"
}
0

, , , . preg_match_all(...), $match .

$input = '1|Common 2|Rare 3|Almost Extinct';
preg_match_all('/\d+\|([^\d]+)/',$input, $match);
print_r($match[1]);

:

Array
(
    [0] => Common 
    [1] => Rare 
    [2] => Almost Extinct    
)

, , .

, , , .

0

Source: https://habr.com/ru/post/1752665/


All Articles