James MV
James MV

Reputation: 8717

PHP String compare with Wildcard

I thought this would be really easy but I can't find a simple solution, I really like PHP but only know the basics.

I'm after a simple something so that I can find:

http://www.myurl.com/*

So just the my url followed by wildcard. So it would return:

 http://www.myurl.com/page1.php
 http://www.myurl.com/page2.php
 http://www.myurl.com/page3.php

but not

http://www.stackoverflow.com

Is regex the way to go or is it overkill?

Upvotes: 1

Views: 627

Answers (1)

MitMaro
MitMaro

Reputation: 5927

Sounds like a startsWith function would work well.

<?php
function startsWith($haystack, $needle, $caseInsensitive = false) {
    // if doing case-insensitive
    if ($caseInsensitive){
        return (strcasecmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
    }
    return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
}

You can use it like:

startsWith('http://www.myurl.com/page1.php', 'http://www.myurl.com/', true);

Upvotes: 2

Related Questions