php - Replacing and removing parts of a string


I have a string made up from a URL like so: and I want to turn it into

What's the best way to remove the last two ' / ' and replace the second to last ' / ' with ' # '?




Remove the Last Slash first and then Replace the Last Slash with a Hash

$url = "";

$url = substr($url, 0, -1);

$add = "#";

$new =  preg_replace("~\/(?!.*\/)~", $add, $url);

echo $new;




Here is a solution usingregex to find the last/.

$url =  '';
$output = preg_replace('!/([^/]+)/$!', "/#\\1", $url);
echo $output."\n";

Here's a little bit of explanation of how this works.

  1. 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/.

  2. 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.

  3. The grouping parenthesis() captures the expression in between the two/, and the replacement expression\1 substitutes it back in during the replacement.




First, find the last position:

$url = "";
$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);   

People are also looking for solutions to the problem: javascript - AJAX connect to PHP OOP WebService


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.