Find array within a string?

Asked

Viewed 42 times

0

I have a column in the database that saves a free text, and together is saved some data within [ ] is to find only what is inside [ ] in this string to convert it to 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 the [236,AD-BF] and turn it into array.

There’s some way to do it?

$array = explode(',',$texto);
  • The funny thing I see here is people negativate without at least leaving a justification, it would be good to know the reason to be able to better where I went wrong, I am not against negativar I am even favorable because it helps us to evolve.

  • you just want a solution for this specific case or want a reusable thing for other phrases?

  • But the text to be extracted always comes within [] ? There’s only ever one block [] ?

  • It would be something that is reusable for other phrases that contain the same string pattern

  • The text to be extracted always comes within [ ] and each string will have only one occurrence

  • Of a researcher in the function preg_split, he is one of the possible solutions

Show 1 more comment

1 answer

5


Capture 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 ]

See in regex101

This gives you the text inside [ and ]. With this text just 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);

Watch it run on Ideone

For capture with regex I used function preg_match, returning the first capture group in position 1, that explains the parameter $capturado[1].

  • 2

    I was looking for an explanation of the logic of regex and with that answer the concept became much clearer. + 1

  • Only one observation if used $capturado[0] will be returned exactly the desired result:[236,AD-BF] , if used print_r($array);é retornadoArray ( [0] => 236 [1] => AD-BF )`

  • 2

    @Thiagodrulla In position 0 has the match complete, which will include the [ and ] and that will be seen in the explode. See the example in ideone

  • The perfect explanation was a lesson, and very well conceived my problem, even I can already use it in other parts of the system. Thank you.

  • Just a tip to further optimize ER. Add ? after '/[(.?)]/' Com '/[(.?)]/' 24 Steps and '/[(.)]/' 94 Steps About "Steps" https://stackoverflow.com/questions/41447805/what-are-steps-in-regexbuddy

Browser other questions tagged

You are not signed in. Login or sign up in order to post.