Take the 2-minute tour ×

I have strings of text that may have the following formats:

Was £39.95 Now Only £29.00
Was 0.95p Now 10p

What is the easiest way to extract two numbers from each string, so I can subtract them later.

share|improve this question
How are you planning to differentiate £29 and 10p? One is 2900p, the other 10 –  Pekka 웃 Oct 30 '10 at 18:44

2 Answers 2

up vote 1 down vote accepted

This monstrosity will capture two numbers separated by text. It will also capture the units.

$match = preg_match("/((?:£)?(\d+(?:\.\d+)?)(?:p)?)[a-z\s]*((?:£)?(\d+(?:\.\d+)?)(?:p)?)/i", "Was £39.95 Now Only 99p");


This will yield:

Array (
    [0] => Was £39.95 Now Only 99p
    [1] => £39.95
    [2] => 39.95
    [3] => 99p
    [4] => 99
share|improve this answer

You can use a regular expression like the following:


Be careful because this won't read the units, so you could easily end up with an error if there is something like the following:

Was £2 Now Only 99p 

You may also want to watch out for commas in your text string. Note that there are also internationalization issues here that you should be aware of. Many countries use , as a decimal separator and . as the thousands separator. You might be able to guess the locale from the currency (e.g. £ suggests that the decimal separator is .).

If you can be more precise about what sort of values your program must accept then you will probably get better answers.

share|improve this answer

Your Answer


