0

Need quick help with regexp, to search a string for

blah blah blah price 4.000 blah blah

and assign 4.000 or whatever number comes after price to a variable.

2
  • preg_match("/price (.*?) /i", $string, $match); Commented Jul 14, 2011 at 3:09
  • As can be seen from the posts below, even after the regular expression match, it behooves one to try converting the extracted data into a number and react to any failures accordingly. Commented Jul 14, 2011 at 3:28

2 Answers 2

3
preg_match('~price\s+(\S+)~', $input, $matches);
var_dump($matches);
Sign up to request clarification or add additional context in comments.

4 Comments

This will match price :-( :-)
@pst: are you sure? ;-) What about $matches[1]?
codepad.viper-7.com/uIitwm - $matches[1] is :-( I should have said "will accept price :-(".
@pst: yep. That's because I've solved the task of parsing the data, not its validation ;-)
1
$num = preg_replace('/price ([\d,\.]+)/', '\1', $string);

or

preg_match('/price ([\d,\.]+)/', $string, $matches);
$num = $matches[1];

6 Comments

It will not match 4.000 ;-)
It will not match 4.000 :-/
will this work if the number contains a decimal point (dot) and a thousand separator (comma)?
@pst - Yep. You don't want to commit the crime of unnecessary escaping :)
@pst - Also, you changed your comment about escaping . while I was replying to it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.