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 ' # '?

238

Answer

Solution:

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
847

Answer

Solution:

Here is a solution usingregex 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.

946

Answer

Solution:

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

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

Source

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.