samedi 25 avril 2015

PHP & regex to extract two separate parts of a string as ONE recombined variable


I have a PHP string consisting of HTML code as follows:

$string =
'<ul>
<li>
<a href="/nalcrom">Nalcrom</a>
        (Sodium Cromoglicate)
</li>
<li>
<a href="/alimemazine">Alimemazine</a>
</li>
<li>
<a href="/xolair">Xolair</a>
        (Omalizumab)
</li>
</ul>';

using

preg_match_all($regex,$string,$matches, PREG_PATTERN_ORDER);

for ($i = 0; $i < count($matches[0]); ++$i)
{ echo $i . "    " . $matches[0][$i]. "<br>"; }

if I use

$regex = "^(?<=>).*?(?=(\Q</a>\E))^";

I get

1 Nalcrom

2 Alimemazine

3 Xolair

whereas if I use

$regex = "^\(.*?\)^";

I get

1 (Sodium Cromoglicate)

2 (Omalizumab)

Trying

$regex = "^(?<=>).*?(?=(\Q</a>\E))(\(.*?\))^";

and variations upon it I get nothing but blank, whereas what I need is:

1 Nalcrom (Sodium Cromoglicate)

2 Alimemazine

3 Xolair (Omalizumab)

Any ideas on how I can do this? thnx


Aucun commentaire:

Enregistrer un commentaire