Reputation: 1095
I have a string made up from a URL like so: http://www.foo.com/parentfoo/childfoo/
and I want to turn it into http://www.foo.com/parentfoo#childfoo
What's the best way to remove the last two ' / ' and replace the second to last ' / ' with ' # '?
Upvotes: 0
Views: 55
Reputation: 75545
Here is a solution using regex
to find the last /
.
<?php
$url = 'http://www.foo.com/parentfoo/childfoo/';
$output = preg_replace('!/([^/]+)/$!', "/#\\1", $url);
echo $output."\n";
?>
Here's a little bit of explanation of how this works.
First, we delimit the regex using !
instead of the usual /
because we are trying to match against /
inside the expression, which saves us certain amount of confusion and headache with escaping the /
.
The expression /([^/]+)/$
. We are matching a literal /
, followed by some nonzero number of non-/
characters, followed by another literal /
, followed by the end of string $
. By tying the match to the end of string, we ensure that the two literal /
we have matched are exactly the last and second-to-last /
in the input.
The grouping parenthesis ()
captures the expression in between the two /
, and the replacement expression \1
substitutes it back in during the replacement.
Upvotes: 1
Reputation: 8960
First, find the last position:
$url = "http://www.foo.com/parentfoo/childfoo/";
$last = strrpos($url, '/');
if ($last === false) {
return false;
}
From there, find the 2nd last:
$next_to_last = strrpos($url, '/', $last - strlen($url) - 1);
$var1 = substr_replace($url,"",$last);
echo $var2 = substr_replace($var1, "#", $next_to_last, 1);
// http://www.foo.com/parentfoo#childfoo
Upvotes: 0
Reputation: 5361
Remove the Last Slash first and then Replace the Last Slash with a Hash
<?php
$url = "http://www.foo.com/parentfoo/childfoo/";
$url = substr($url, 0, -1);
$add = "#";
$new = preg_replace("~\/(?!.*\/)~", $add, $url);
echo $new;
?>
Output
http://www.foo.com/parentfoo#childfoo
Upvotes: 2