tags:

views:

35

answers:

1

How do I add the character - within the preg_match?

preg_match('#^(\w+/){0,2}\w+\.\w+$#', $string)

But it must be before the last . within the string. I've tried just about everything I know here. I know that the - needs to be escaped. So I tried to escape it in various places, but it's not working :(

argggg

+3  A: 

Your knowlegde that the dash needs to be escaped is incomplete.

preg_match('#^(\w+/){0,2}\w+-\.\w+$#', $string)

It needs to be escaped in character classes, because it has a special meaning there, but it has no special meaning in the rest of the regex, so it needs no escaping here.

Tomalak
Sorry, this is not working at all.
SoLoGHoST
Then your question is incomplete. Post the strings you are trying to match.
Tomalak
I'm sorry, I think it's working, what's the best way to check for this? If a return == 1? Would that work? Does this return how many matches, or does it return 1 for any and all matches?
SoLoGHoST
It does return 0 for 0 matches, or 1 for "match found". It does not count matches, it stops after the first. Please have a look at the documentation, this can also return FALSE under certain conditions.
Tomalak
Also, I've only been reading up on PCRE recently, and all instances I see a `\-` so it makes me think that it must need to be escaped. I don't understand this, arggg.
SoLoGHoST
Thanks, this works perfect, Cheers :)
SoLoGHoST
No, you see `\-` only in character classes. Look more closely.
Tomalak
Also, would this work for a `preg_replace` than: `#^/|/$|[^A-Za-z0-9_.-/]#` or does this 1 need to be escaped?
SoLoGHoST
It is in a character class, so it needs to be escaped. Seriously, at the very least read the page I linked to in my answer as well as the documentation of the preg_* functions.
Tomalak