Reputation: 1467
I have a string like:
<price>£10</price>Rimmel Super-Quick Mascara
I want to extract the string out of the <price>
tags and also retain the string after the tags too. So:
$price = £10
$desc = Rimmel Super-Quick Mascara
How can I do this with PHP? I have attempted to use the following function I found but I get an unknown error in the regex, though I can't identify where.
function getTextBetweenTags($string, $tagname) {
$pattern = "/<$tagname ?.*>(.*)<\/$tagname>/";
preg_match($pattern, $string, $matches);
return $matches[1];
}
Upvotes: 0
Views: 36
Reputation: 2058
Try this for both price and text:
$str = '<price>£10</price>Rimmel Super-Quick Mascara';
$text = preg_replace('/<[a-z]+>(.*?)<\/?[a-z]+>(.*?)/','$1|$2',$str);
$data = explode('|',$text);
var_dump($data);
response:
array (size=2)
0 => string '£10' (length=3)
1 => string 'Rimmel Super-Quick Mascara' (length=26)
In your function :
function getTextBetweenTags($string, $tagname) {
$text = preg_replace("/<".$tagname.">(.*?)<\/?".$tagname.">(.*?)/","$1|$2",$string);
$data = explode('|',$text);
return $data;
}
Upvotes: 1
Reputation: 866
Try this
$pattern = "/.*?<$tagname.*?>(.*?)<\/$tagname.*?>/";
preg_match_all($pattern, $string, $matches );
return $matches[ 0 ][ 0 ];
Upvotes: 0