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\"

D T
  • 3,522
  • 7
  • 45
  • 89

2 Answers2

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.

Community
  • 1
  • 1
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • I only delete last '\\tables' – D T May 07 '14 at 12:06
  • Nitpick: This wouldn't still work. To match a literal backslash, you'd have to write ``\\\\``. (As for why, see [this answer](http://stackoverflow.com/a/20819109/1438393).) ;-) – Amal Murali May 07 '14 at 12:16
  • @AmalMurali Hey, thx!. wouldn't have expected that. But sounds logic now :) – hek2mgl May 07 '14 at 12:23
  • If i echo tag_path="c:\work\link2\tmp\5699", But i write log tag_path="c:\work\link2\\tmp\\5699\" – D T May 08 '14 at 03:03
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

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126