Reputation: 3746
$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\"
Upvotes: 0
Views: 103
Reputation: 157947
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.
Upvotes: 2
Reputation: 68466
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,'\\'));
Upvotes: 1