I am trying to search for some pattern in PHP with the help of preg_match. Search pattern is like this (but this is wrong):
/[\d\s*-\s*\d\s*(usd|eur)]{1}/i
\d starts with integer,
\s* there can be any number of whitespaces,
- there must be exactly one minus sign
\s* there can be any number of whitespaces,
\d then must be integer
\s* there can be any number of whitespaces,
(usd|eur) any of the following words must be present but one
[\d\s*-\s*\d\s*(usd|eur)]{1} - in string there should be exactly one occurence
the above pattern does not work, what I am doing wrong? For testing:
<?php
$pattern = '/[\d\s*-\s*\d\s*(usd|eur)]{1}/i';
$query = '100-120 100-120';
echo $pattern.'<br/>';
echo $query.'<br/>';
if(preg_match($pattern, $query))
echo 'OK';
else
echo 'not OK!';
?>
Note: I am trying to pull out data like this:
The price of item is 100 - 120 usd in our market
[...]
is a character class. It means "match any one of these characters". [abc]
will match a,b, or c. It doesn't match the string "abc".
In addition:
{1}
means "match the preceding expression one time". However, matching once is the default. There is no need to explicitly tell it to match one time.
\d
matches a single numeric digit. Based on your example, you want \d+
- match a number made up of at least one digit.
Here is what your pattern should look like:
/\d+\s*-\s*\d+\s*(usd|eur)/i