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.

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

2 Answers2

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!';
knittl
  • 246,190
  • 53
  • 318
  • 364
  • 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 Jan 27 '13 at 10:30
  • @Roland: It works for me. I don't get that error (with or without trailing slash): http://codepad.org/UMD5xpgA – knittl Jan 27 '13 at 11:06
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!

Frederik Kammer
  • 3,117
  • 3
  • 28
  • 29
  • BTW: The question was already answered: http://stackoverflow.com/questions/7790761/how-to-replace-only-the-last-match-of-a-string-with-preg-replace?rq=1 – Frederik Kammer Jan 27 '13 at 10:28
  • 1
    This will also match `https://api.mongohq.com/abc` – not sure if that is the anticipated behavior: http://codepad.org/OvUFHdU8 – knittl Jan 27 '13 at 11:09
  • Thanks for your comment. I updated my answer so that all characters behind the slash will be replaced, too – Frederik Kammer Jan 27 '13 at 11:30
  • @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. – knittl Jan 27 '13 at 11:58