php - Replacing and removing parts of a string
381
I have a string made up from a URL like so:http://www.foo.com/parentfoo/childfoo/
and I want to turn it intohttp://www.foo.com/parentfoo#childfoo
What's the best way to remove the last two ' / ' and replace the second to last ' / ' with ' # '?
Answer
Solution:
Remove the Last Slash first and then Replace the Last Slash with a Hash
Output
Answer
Solution:
Here is a solution using
regex
to find the last/
.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.Answer
Solution:
First, find the last position:
From there, find the 2nd last: