Tom
Tom

Reputation: 1095

Replacing and removing parts of a string

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

Answers (3)

merlin2011
merlin2011

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.

  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.

Upvotes: 1

Parag Tyagi
Parag Tyagi

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

Tasos
Tasos

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

Related Questions