PHP & regex to extract two separate parts of a string as ONE recombined variable -
i have php string consisting of html code 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); ($i = 0; $i < count($matches[0]); ++$i) { echo $i . " " . $matches[0][$i]. "<br>"; }
if use
$regex = "^(?<=>).*?(?=(\q</a>\e))^";
i get
1 nalcrom
2 alimemazine
3 xolair
whereas if use
$regex = "^\(.*?\)^";
i get
1 (sodium cromoglicate)
2 (omalizumab)
trying
$regex = "^(?<=>).*?(?=(\q</a>\e))(\(.*?\))^";
and variations upon nothing blank, whereas need is:
1 nalcrom (sodium cromoglicate)
2 alimemazine
3 xolair (omalizumab)
any ideas on how can this? thnx
make second regex group optional ?
, i.e.:
$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>'; preg_match_all('%">(.*?)</a>\s+(\(.*?\))?%i', $string, $match, preg_pattern_order); ($i = 0; $i < count($match[0]); $i++) { echo $match[1][$i] . " ". $match[2][$i]; }
output:
nalcrom (sodium cromoglicate) alimemazine xolair (omalizumab)
Comments
Post a Comment