Welcome to WebmasterWorld Guest from 54.163.84.199

Forum Moderators: coopster & jatar k

Extract a Number Between Tags

   
1:37 am on Nov 9, 2009 (gmt 0)

5+ Year Member



Hi,

I have the following code:

$text="<ListPrice>15</ListPrice>";
preg_match('/<ListPrice>(\d+)<\/ListPrice>/s',$text,$matches);
echo $matches[0];

My goal is to extract the number inside the ListPrice tags in a decimal format,not as a string.The code above outputs 15,however, when I try to convert it to a decimal using the intval command,for some reason I get the value zero.How do I solve this?

Thanks.

1:55 am on Nov 9, 2009 (gmt 0)

WebmasterWorld Senior Member themadscientist is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month




<?php
$text="<ListPrice>15</ListPrice>";
preg_match('/<ListPrice>(\d+)<\/ListPrice>/s',$text,$matches);

if(is_string($matches[1])) {
$matches[1]=intval($matches[1]);
echo 'Converted to intval();<br>';
echo $matches[1]."<br>";
echo htmlentities($matches[0]);
}

else {
echo 'Already a Numeric Value<br>';
echo $matches[1]."<br>";
echo htmlentities($matches[0]);
}
?>

EDITED

2:08 am on Nov 9, 2009 (gmt 0)

5+ Year Member



TheMadScientist already offered a correct solution, but to see why yours wasn't working, try using:
echo htmlspecialchars($matches[0]);

instead.

As explained by the preg_match documentation [us.php.net] (emphasis mine):

$matches[0] will contain the text that matched the full pattern
 

Featured Threads

Hot Threads This Week

Hot Threads This Month