tags:

views:

62

answers:

2

How do I put a period into a PHP regular expression?

The way it is used in the code is:

echo(preg_match("/\$\d{1,}\./", '$645.', $matches));

But apparently the period in that $645. doesn't get recognized. Requesting tips on how to make this work.

+1  A: 
jensgram
What I have is /\$[0-9]{1,}\./ but when I put in $645. it doesn't recognize the regex. I'm 12 and what is this?
TOKYOTRIBE4EVAR
Ahh, @Gumbo elaborated on his answer too :(
jensgram
So how does it not recognize the closing period on my string?
TOKYOTRIBE4EVAR
@TOKYOTRIBE4EVAR Please add examples to your question body. Also, are you serious? (*"I'm 12 and what is this?"*)
jensgram
Lol no, it's just a kewl new meme that I learned about at my school's /b/ club today.
TOKYOTRIBE4EVAR
We also watched this funny video called goosh goosh and looked at all these cat pictures. /b/ is the best site!
TOKYOTRIBE4EVAR
Oh as for examples, here's how I used it in my code
TOKYOTRIBE4EVAR
echo(preg_match("/\$\d{1,}\./", '$645.', $matches));
TOKYOTRIBE4EVAR
@TOKYOTRIBE4EVAR Be aware of the double-quoting (see my answer). Also, the interesting part is the `$matches`, not the return value from `preg_match()`.
jensgram
@TOKYOTRIBE4EVAR Try `'/\$\d{1,}\./'`
jensgram
The $matches is really kinda just there foar now but later I will have that in thar for reals. When I did that echo, everything up to the period returns a 1 but once I add in the period there's a 0.
TOKYOTRIBE4EVAR
@TOKYOTRIBE4EVAR Working here: http://www.ideone.com/O1bEF
jensgram
So I need to has single quotes around my regex?
TOKYOTRIBE4EVAR
@TOKYOTRIBE4EVAR Either that or escape properly. See my updated answer.
jensgram
+3  A: 

Since . is a special character, you need to escape it to have it literally, so \..

Remember to also escape the escape character if you want to use it in a string. So if you want to write the regular expression foo\.bar in a string declaration, it needs to be "foo\\.bar".

Gumbo
What I have is /\$\d{1,}\./ but when I put in $645. it doesn't recognize the regex on the period. I'm 12 and what is this?
TOKYOTRIBE4EVAR
@TOKYOTRIBE4EVAR: How do you use that regular expression?
Gumbo
echo(preg_match("/\$\d{1,}\./", '$645.', $matches));
TOKYOTRIBE4EVAR
@TOKYOTRIBE4EVAR: Note that `preg_match` does only return whether a match has been found or not (either `1` or `0`). You need to look at the array `$matches` to see what has been matched.
Gumbo
It returned a 0, which means that there was no match. Is there something wrong with my period escape or am I just getting trolled really hard?
TOKYOTRIBE4EVAR
You need to escape the `\ ` in `\$` too: `"/\\\$\d{1,}\./"`. With only `\$` it is replaced inside *double quotes* to `$` that means the end of the string. This would be fine in single quotes, e.g. `'\$'` → `\$`, as `\$` is not a known escape sequence. But in double quotes it is, so that `"\$"` → `$`.
Gumbo