wowzuzz
wowzuzz

Reputation: 1388

Checking to see if path is in url

I have a path that I want to check for in a url. How would I isolate

'pages/morepages/' http://www.mypage.com/pages/morepages/

I've tried running a parse url function on my url and then I get the path. I don't know how to access that key in that array though. For example..

$url = 'http://www.mypage.com/pages/morepages/';

print_r(parse_url($url));

if ($url['path'] == '/pages/morepages/') {
    echo 'This works.';
};

I want to run an if conditional on if that path exists, but I am having trouble accessing it.

Upvotes: 1

Views: 1855

Answers (7)

blockhead
blockhead

Reputation: 9705

You are not assigning the output of parse_url to a variable. $url is still equal to the string (parse_url returns an array, it doesn't modify the string passed in).

$url = parse_url($url);

Upvotes: 0

Sampson
Sampson

Reputation: 268482

If you're just looking for one string within another, strpos() will work pretty well.

echo strpos( $url, $path ) !== false ? 'Exists' : 'Does Not Exist' ;

Upvotes: 3

Chris C
Chris C

Reputation: 2013

Parse_url needs to return something to a new array variable. So use:

$parsedUrl = parse_url($url));

if ($parsedUrl['path'] == '/pages/morepages/') {
    echo 'This works.';
};

Upvotes: 0

Jivago
Jivago

Reputation: 826

Here you go

$url = 'http://www.mypage.com/pages/morepages/';

    if (strpos($url, '/pages/morepages/') !== false) {
        echo "found";
    } else {
        echo "not found";
    }

Upvotes: 2

Pheonix
Pheonix

Reputation: 6052

something like find in string ?

if ( strpos($url['path'], '/pages/morepages/') !== false ){
//echo "this works";
}

Upvotes: 2

ioseb
ioseb

Reputation: 16949

Just assign function's result to any variable:

$parts = parse_url($url);

if ($parts['path'] == '/pages/morepages') {
}

Upvotes: 0

Tom van der Woerdt
Tom van der Woerdt

Reputation: 29985

You can simply use

if (parse_url($url['path'], PHP_URL_PATH) == '/pages/morepages/') {
    echo 'This works.';
} // No semicolon

It's probably better to use strpos() though, which is a LOT faster.

Upvotes: 0

Related Questions