Lucas Melo Lucas Melo - 5 months ago 13
PHP Question

regex to catch words in pre defined placeholders

I'm creating a function in PHP that takes a string . Then the function must look within that string , words within brackets and saves them in an array. Is there any function to conduct the search only those words and save them to an array? or in a variable and then I pass it to an array ?

String example

<font color="maroon">[como]</font> &lt;rel&gt; &lt;ks&gt; <font color="blue"><b>ADV</b> </font> <font color="darkgreen">@ADVL&gt;</font> <font color="darkgreen"><b>@#FS-ADVL</font></b> <font color="darkgreen"><b>@#FS-N&lt;</font></b>
<dt><b><font color="maroon">não</font></b>

<font color="maroon">[não]</font> <font color="blue"><b>ADV</b> </font> <font color="darkgreen">@ADVL&gt;</font>
<dt><b><font color="maroon">amar</font></b>

<font color="maroon">[amar]</font> &lt;vt&gt; <font color="blue"><b>V</b> FUT 1/3S SUBJ VFIN </font> <font color="darkgreen">@FMV</font>
<dt><b><font color="maroon">uma</font></b>

<font color="maroon">[um]</font> &lt;arti&gt; <font color="blue"><b>DET</b> F S </font> <font color="darkgreen">@&gt;N</font>
<dt><b><font color="maroon">pessoa</font></b>

<font color="maroon">[pessoa]</font> &lt;H&gt; <font color="blue"><b>N</b> F S </font> <font color="darkgreen">@&lt;ACC</font>
<dt><b><font color="maroon">tão</font></b>

<font color="maroon">[tão]</font> &lt;dem&gt; &lt;quant&gt; <font color="blue"><b>ADV</b> </font> <font color="darkgreen">@&gt;A</font>
<dt><b><font color="maroon">linda</font></b>

<font color="maroon">[lindo]</font> <font color="blue"><b>ADJ</b> F S </font> <font color="darkgreen">@N&lt;</font>
<dt><b><font color="maroon">.</font></b>

Array example

[0] => como
[1] => não
[2] => amar
[3] => um
[5] => pessoa
[6] => tão
[7] => lindo



The function that you are looking for is the preg_match_all() function

$htmlToParse = 'Some [html] here to be [captured] and [filtered]';
preg_match_all("/\[([^\]]*)\]/", $htmlToParse, $matchesWords);


and there will be something like this

    [0] => html
    [1] => captured
    [2] => filtered

See the full documentation of preg_match_all() function and keep studying some of regular expression