vellai durai vellai durai - 5 months ago 8
PHP Question

extract values from srting seperated by | in php

How to extract values from string seperated by |

here is my string

$var='foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';


i need to store

$foo=1478
$boo=7854
$ccc=74125

Answer

Of course every body would suggest the explode route:

$var = 'foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
foreach(array_filter(explode('|', $var)) as $e){
    list($key, $value) = explode('=', $e);
    ${$key} = $value;
}

Also, another would be to convert pipes to ampersand, so that it can be interpreted with parse_str:

parse_str(str_replace('|', '&', $var), $data);
extract($data);
echo $foo;

Both would produce the same. I'd stay away with variable variables though, it choose to go with arrays.