Problem with $ in preg_match

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
bschaeffer
Forum Newbie
Posts: 24
Joined: Thu Apr 30, 2009 9:10 pm

Problem with $ in preg_match

Post by bschaeffer »

I've got a form with a URL submission field. I take the submitted url, append a string to it, and get some information back from it.

My question comes when checking for the final forward slash in the root in the submission. I need to be able to append the string after the last forward slash because it won't work if I don't.

Here's what I have, but it's obviously not working.

Code: Select all

<?php
$url = "http://www.php.net/";
// Trying to check for a '/' at the end of the submitted url 
$pattern = '//$/'; // I've also tried '/[/]$/' as the pattern
$check = preg_match( $pattern , $url );
 
if($check) {
    echo "This url ends in a forward slash";
    return true;
}
else {
    echo "This url doesn't end in a forward slash";
    return false;
}
?>
This should return true, or at least thats what I am expecting. It seems to me that this code should work. I've checked it in numerous online REGEX editors and it does exactly what I want it to do. But when I try to implement into my code, I get an error message that reads:
Warning: preg_match() [function.preg-match]: Unknown modifier '$'
I've been searching online for "end of string" indicators for php and regex, and even there it looks like this is the pattern I should be using.

Any ideas?

Thanks in advance.
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Problem with $ in preg_match

Post by prometheuzz »

You're using a forward slash as the delimiter of your regex pattern, so if you want to match a forward slash, you'll need to escape it like this:

Code: Select all

$pattern = '/\/$/';
or use a different delimiter:

Code: Select all

$pattern = '#/$#';
in which case you don't need to escape the forward slash.
User avatar
bschaeffer
Forum Newbie
Posts: 24
Joined: Thu Apr 30, 2009 9:10 pm

Re: Problem with $ in preg_match

Post by bschaeffer »

That's awesome.

I'm a complete noob here, so just remember that when I say I had no idea you could switch out delimiters.

Really, though, thanks a bunch!
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Problem with $ in preg_match

Post by prometheuzz »

bschaeffer wrote:That's awesome.

I'm a complete noob here, so just remember that when I say I had no idea you could switch out delimiters.

Really, though, thanks a bunch!
You're welcome.
Post Reply