0
$tag_path = "c:\work\link2\\tmp\\5699\\tables";

I want to delete only the last \\tables in $tag_path.

I used the code below:

$tag_path = preg_replace("/\\\\tables$/i", "", $tag_path);

But it returned the following result:

c:\work\link2\\tmp\\5699\

Why? How can I delete the last \\tables in $tag_path?

If i echo tag_path="c:\work\link2\tmp\5699", But i write log tag_path="c:\work\link2\\tmp\\5699\"

9
  • Use str_replace() instead: str_replace('\\tables', '', $tag_path);. Commented May 7, 2014 at 12:04
  • I only want to delete last '\\tables'. If tag_path has 2 '\\tables' Commented May 7, 2014 at 12:07
  • 1
    possible duplicate of Extra backslash needed in PHP regexp pattern Commented May 7, 2014 at 12:07
  • @user1497597: I'm not sure how it doesn't work. See this demo. Your preg_replace statement works as it should. Commented May 7, 2014 at 12:08
  • have not answer correct Commented May 7, 2014 at 12:08

2 Answers 2

2

Just:

str_replace('\\tables', '', $tag_path);

... should do the job. Note that I'm using single quotes and I'm using str_replace() in favour of preg_replace() because you are about to replace a constant pattern, no regex. In this case str_replace() is simpler and therefore faster.


Update:

In comments you told that you want to replace \\tables only if it is the end of the path. Then a regex is the right solution. Use this one:

preg_replace('~\\\\tables$~', '', $tag_path);

Also here the single quotes do the trick. Check this answer which explains that nicely. Furthermore I'm using ~ as the pattern delimiter for more clearness.

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

4 Comments

I only delete last '\\tables'
Nitpick: This wouldn't still work. To match a literal backslash, you'd have to write \\\\. (As for why, see this answer.) ;-)
@AmalMurali Hey, thx!. wouldn't have expected that. But sounds logic now :)
If i echo tag_path="c:\work\link2\tmp\5699", But i write log tag_path="c:\work\link2\\tmp\\5699\"
1

Use strrpos() as a lookbehind for the last \\. (No strict rule)

This even works if your tables is TABLES , tab or any other data after the last \\

echo substr($tag_path,0,strrpos($tag_path,'\\'));

Demonstration

5 Comments

If i echo tag_path="c:\work\link2\tmp\5699", But i write log tag_path="c:\work\link2\\tmp\\5699\"
@user1497597, It's easy add a slash at the end. See this demo
No, I use code: substr($tag_path,0,strrpos($tag_path,'\\')); if i write log result still: tag_path="c:\work\link2\\tmp\\5699\"
If i use echo tag_path="c:\work\link2\tmp\5699", But i write log tag_path="c:\work\link2\\tmp\\5699\". I echo result the same demo. But write log, it still error.
What is your expected output ?

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.