Helminthophobe Posted February 20, 2008 Share Posted February 20, 2008 I'm extremely new to regex so I apologize if I use incorrect terminology or don't explain myself very well. I'm building a little script that takes preformatted text from another site and reformats it for my own use. It looks for numbers within that text. Here are a couple of examples that may show up. Metal: 395.813 Crystal: 44.398 Metal: 395 Crystal: 44.398 Metal: 2.395.813 Crystal: 44.398 This is the code I am using now. $match = array(); if(preg_match("/Metal:\s+(.+)\s/",$text,$match)) { $metal = $match[1]; } echo "<b>Metal ". $metal . "</b>"; It outputs the following: Metal 395.813 Crystal: 189.516 How would I get it to just output the number and not the information after the number too? Any help would be greatly appreciated! Quote Link to comment Share on other sites More sharing options...
dsaba Posted February 20, 2008 Share Posted February 20, 2008 /Metal:\s+(.+)\s/ you problem is with the .+ part consuming too much, . means any character including spaces, you have to control just what you consume observe: http://nancywalshee03.freehostia.com/regextester/regex_tester.php?seeSaved=3agz3yjn also preg_match_all() will extract all matches from the haystack, not just the first one, this wasn't your problem though, however you may find it beneficial to use preg_match_all() in many scenarios try this: (~ is a delimiter just like /) ~Metal:\s+([^\s]+)\s~ //$out[0][0] is the first match's subgroup get more specific with identifying number patterns: ~Metal:\s+([\.\d]+)~ See: http://nancywalshee03.freehostia.com/regextester/regex_tester.php?seeSaved=33wp0ony <?php $hay = 'Metal: 395.813 Crystal: 44.398'; $pat = '~Metal:\s+([\.\d]+)~'; preg_match_all($pat, $hay, $out); echo $out[0][0]; ?> Quote Link to comment Share on other sites More sharing options...
Helminthophobe Posted February 20, 2008 Author Share Posted February 20, 2008 So [\.\d]+ looks for single numbers and the "." while the + tells it to repeat that until there are no more numbers or ".", correct? I appreciate the speedy answer. Your code worked perfect and that link you used is going to be a huge help too. I really appreciate it! Quote Link to comment Share on other sites More sharing options...
dsaba Posted February 20, 2008 Share Posted February 20, 2008 Yes you are correct, if you press FAQ on the website it will take you too a regex reference, or go to "Resources" here on phpfreaks->regex help , or google \d is shorthand for numbers * means to repeat 0 or more times + means 1 or more time -no problem return the favor by doing the same Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.