homepage Welcome to WebmasterWorld Guest from 54.163.91.250
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
Extract a Number Between Tags
Mister_L




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

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.

 

TheMadScientist




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


<?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

pinterface




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

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

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved