Find array inside a string?

0

I have a column in the database that saves free text, and together it saves some data within [ ] is to find only what is inside [ ] in this string to convert it into an array.

Example:

$texto = "Hoje fomos até São Paulo visitar o paciente, [236,AD-BF] e não foi possível chegar a um diagnóstico";

I would like to extract only [236,AD-BF] and turn it into array.

Is there any way to do it?

$array = explode(',',$texto);
    
asked by anonymous 26.10.2018 / 16:30

1 answer

5
Capturing what is inside [ and ] is simple to do with a regex like:

\[(.*)\]

Explanation:

\[   - Apanhar o caratere literal [
(.*) - Capturar tudo o que vem a seguir
\]   - Até encontrar o caratere literal ]

View on regex101

This gives you the text inside [ and ] . With this text, it is enough to use explode with "," to get the desired array.

Example:

$texto = "Hoje fomos até São Paulo visitar o paciente, [236,AD-BF] e não foi possível chegar a um diagnóstico";
preg_match("/\[(.*)\]/", $texto, $capturado);

$array = explode(",", $capturado[1]);
print_r($array);

See Running on Ideone

For capture with regex I used preg_match function, which returns the first group 1 , which explains the $capturado[1] parameter.

    
26.10.2018 / 17:08