0

I am trying to replace /admin and \admin from the following two strings:

F:\dev\htdocs\cms\admin
http://localhost/cms/admin 

Using the following regular expression in preg_replace:

/[\/\\][a-zA-Z0-9_-]*$/i

1) From the first string it just replaces admin where as it should replace \admin

2) From the second string it replaces every thing except http: where as it should replace only /admin

I have checked this expression on http://regexpal.com/ and it works perfect there but not in PHP.

Any idea?

Note that the last part of each string admin is not fixed, it can be any user selected value and thats why I have used [a-zA-Z0-9_-]* in regular expression.

3
  • In the first bracket, i require either a \ or / but only one at a time Commented Dec 28, 2013 at 16:54
  • You regex works. Commented Dec 28, 2013 at 17:01
  • @glavic yes it works but not in PHP preg_replace. Why? Commented Dec 28, 2013 at 17:06

2 Answers 2

6

The original regular expression should be /[\/\\][a-zA-Z0-9_-]*$/i, but since you need to escape the backslashes in string declarations as well, each backslash must be expressed with \\ -- 4 backslashes in total.

From the PHP manual:

Single and double quoted PHP strings have special meaning of backslash. Thus if \ has to be matched with a regular expression \\, then "\\\\" or '\\\\' must be used in PHP code.

So, your preg_replace() statement should look like:

echo preg_replace('/[\/\\\\][a-zA-Z0-9_-]*$/i', '', $str);

Your regex can be improved as follows:

echo preg_replace('~[/\\\\][\w-]*$~', '', $str);

Here, \w matches the ASCII characters [A-Za-z0-9_]. You can also avoid having to escape the forward slash / by using a different delimiter -- I've used ~ above.

Sign up to request clarification or add additional context in comments.

4 Comments

Imho that's only right for patterns in double-quotes. Using single-quotes 3 backslashes should be fine, why not? E.g. echo preg_replace('/(\\\)([\\\])/', '\1_\2_', "\\\\");
@AmalMurali: since you used \w escape sequence, you don't need /i modifier anymore.
@Jonny5: That works, too, but requires changing the OP's original regex. Since \] is an invalid escape sequence, it will remain as it is, and that's probably why it works (although I'm not too sure about it).
Assuming you have a string \test, and want to replace \t : "~\\\t~" will NOT work, whereas "~\\\\t~" and '~\\\t~' will work. Imho the escape level for escaping a backslash when using single-quoted pattern is 1 level less.
0
[\/\\\][a-zA-Z0-9_-]*$/i

Live demo

Comments

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.