Index: wp-includes/post.php
===================================================================
--- wp-includes/post.php	(revision 18627)
+++ wp-includes/post.php	(working copy)
@@ -3155,40 +3155,42 @@
 	$parts = array_map( 'esc_sql', $parts );
 	$parts = array_map( 'sanitize_title', $parts );
 
+	if ( empty($parts) )
+		return null;
+
 	$in_string = "'". implode( "','", $parts ) . "'";
 	$pages = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_name IN ({$in_string}) AND (post_type = %s OR post_type = 'attachment')", $post_type ), OBJECT_K );
 
+	if ( empty($pages) )
+		return null;
+
 	$revparts = array_reverse( $parts );
+	$revparts_count = count($revparts);
 
-	$foundid = 0;
-	foreach ( (array) $pages as $page ) {
-		if ( $page->post_name == $revparts[0] ) {
+	if ( 1 == $revparts_count ) {
+		foreach ( $pages as $page ) {
+			if ( $page->post_name == $revparts[0] )
+				return get_page($page->ID, $output, $post_type);
+		}
+		return null;
+	}
+
+	foreach ( $pages as $page ) {
+		if ( $page->post_name == $revparts[0] && $page->post_parent !=  0) {
+			$cur_page = $page;
 			$count = 0;
-			if ( $page->post_parent != 0 ) {
-				if ( null === ( $parent_page = $pages[ $page->post_parent ] ) )
-					continue;
+			while ( isset($pages[ $cur_page->post_parent ]) ) {
+				if ( $cur_page->post_name != $revparts[ $count ] )
+					continue 2; // Continue next foreach()
+				$count++;
+				$cur_page = $pages[ $cur_page->post_parent ];
+			}
 
-				while ( $parent_page->ID != 0 ) {
-					$count++;
-					if ( $parent_page->post_name != $revparts[ $count ] )
-						break;
-					$parent_page = $pages[ $parent_page->post_parent ];
-				}
-
-				if ( $parent_page->ID == 0 && $count+1 == count($revparts) ) {
-					$foundid = $page->ID;
-					break;
-				}
-			} else if ( count($revparts) == 1 ) {
-				$foundid = $page->ID;
-				break;
-			}
+			if ( $count+1 == $revparts_count && $cur_page->post_name == $revparts[$count] )
+				return get_page($page->ID, $output, $post_type);
 		}
 	}
 
-	if ( $foundid )
-		return get_page($foundid, $output, $post_type);
-
 	return null;
 }
 
