Jump to content

Finding a Number


Helminthophobe

Recommended Posts

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!

Link to comment
Share on other sites

/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];
?>

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.