Get the value of a string within a PHP variable

1
$a = " A=1 B=2";

I need to use echo in $a and display the value of B. I do not want to use array. It's because I'm going to create a column in the database where it will house all the active options. And I do not want to have the job of creating more than 10 columns just for the options. Then it would look like this, the value of COLUMN opcoes will have option1 = true option2 = false ...

    
asked by anonymous 30.12.2017 / 23:37

2 answers

1

You can use parse_str () , but you would have to replace of spaces in white for & :

<?php
$a = " A=1 B=2";
$a = str_replace(' ','&',$a);
parse_str($a, $valor);
echo $valor['B'];
?>

See Ideone .

    
30.12.2017 / 23:56
1

@dvd's response works correctly. But there is another approach that can be used with arrays. You can use the serialize function to convert from array to string (and save to the bank) and unserialize it to convert from string to array. The advantage of this is that you can release the comma without having to escape your options.

An example of this would be:

//dados vindos do formulario
$opcoes = $_POST;

//opções seria algo equivalente 
//a ['opcao1'=>'valor 1', 'opcao 2' => valor2]
$opcoes = serialize($opcoes);//$opcoes agora é uma string

//então salve no banco

//e depois que você ler o campo do banco deserialize assim
$opcoes = $campoLidoDoBanco;//$opcoes é uma string
$opcoes = unserialize($opcoes);//$opcoes agora é um array
    
31.12.2017 / 01:28