Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression and forward slash

i'm searching for keywords in a string via a regular expression. It works fine for all keywords, exept one which contains a forward slash in it: "time/emit" .

Even using preg_quote($find,'/'), which escapes it, i still get the message:

Unknown modifier 't' in /frontend.functions.php  on line 71

If i print the find pattern, it shows /time\\/emit/ . Without preg_quote, it shows /time/emit/ and both return the same error message.

Any bit of knowledge would be useful.

like image 656
pixeline Avatar asked Jun 29 '10 22:06

pixeline


People also ask

How do you handle forward slash in regex?

You can escape it by preceding it with a \ (making it \/ ), or you could use new RegExp('/') to avoid escaping the regex.

Should I escape forward slash in regex?

/Delimiters/ Delimiters have an impact on escaping: if the delimiter is / and the regex needs to look for / literals, then the forward slash must be escaped before it can be a literal ( \/ ).

How do I add a forward slash in a regular expression in Java?

replaceAll("/", "\\/");

What does forward slash mean in JavaScript?

Think of the forward slash as quotation marks for regular expressions. The slashes contain the expression but are not themselves part of the expression. (If you want to test for a forward slash, you have to escape it with a backwards slash.)


2 Answers

Try to begin and end your regular expression with different sign than /

I personally use `

I've seen people using #

I think most chars are good. You can read more about it here: http://pl.php.net/manual/en/regexp.reference.delimiters.php

Like this:

 preg_match('#time/emit#', $subject);  // instead of /time/emit/

To put it another way: Your $find variable should contain rather #time/emit# than /time/emit/

like image 189
Kamil Szot Avatar answered Oct 08 '22 02:10

Kamil Szot


looks like you have something already escaping it..

preg_quote('time/emit') // returns time\/emit
preg_quote('time\/emit') // returns time\\/emit

as a hack you could simply do:

preg_quote(stripslashes($find)) // will return time\/emit
like image 27
nathan Avatar answered Oct 08 '22 00:10

nathan