2

I have a hard time getting around regular expressions and I'm trying to remove the last forward slash in a string :

$public_url = "https://api.mongohq.com/";

What I intend is remove the last forward slash and replace it with something else. I figured I could use preg_replace but I cannot find the right pattern for doing it.

4
  • 1
    rtrim($public_url,'/'); http://ca3.php.net/manual/en/function.rtrim.php Commented Jan 27, 2013 at 10:17
  • @JonHulka ~ I was looking for a regex so I can replace with something rather than adding at the end of string :) Commented Jan 27, 2013 at 10:19
  • 1
    "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems." Commented Jan 27, 2013 at 10:28
  • @nkr ~ you're right :)) I never had the time to sit and learn RegEx :| I hope I will soon though Commented Jan 27, 2013 at 10:47

2 Answers 2

5

You can use a negative lookafter-expression:

<?php
$public_url = "https://api.mongohq.com/";
$replace = "foobar";

echo preg_replace("~\/(?!.*\/)~", $replace, $public_url);
?>

Output:
https://api.mongohq.comfoobar

Update:
Use the following regex to avoid problems with characters behind the last slash:

echo preg_replace("~\/(?!.*\/)(.*)~", $replace, $public_url);

All characters behind the last slash are replaced, too. Thanks to knittl!

Sign up to request clarification or add additional context in comments.

4 Comments

BTW: The question was already answered: stackoverflow.com/questions/7790761/…
This will also match https://api.mongohq.com/abc – not sure if that is the anticipated behavior: codepad.org/OvUFHdU8
Thanks for your comment. I updated my answer so that all characters behind the slash will be replaced, too
@Freeddy: I'm still not sure this is what the OP wants. But the question is not phrased 100 % correct and your answer got accepted, so maybe I'm assuming something wrong.
5

$ anchors regular expression patterns at the end of the string:

$public_url = preg_replace('#/$#', 'replace it!', $public_url);

Also possible:

$public_url = rtrim($public_url, '/').'replace it!';

2 Comments

This is what I get : preg_replace(): Unknown modifier '$' in C:\Users\rgr\Apache\htdocs\Roland Groza [ 3.0 ]\class\mongohq\mongohq.php on line 230
@Roland: It works for me. I don't get that error (with or without trailing slash): codepad.org/UMD5xpgA

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.