Dummy question on rewriting a string

I’ve just created this function to create a SEO-friendly url:

function url_safe($str) {
    
    // only allow numeralpha charaters
    $str = preg_replace("/[^a-zA-Z0-9]/", "-", $str);
    
    // remove unneccsary white space
    $str = preg_replace('/\\s\\s+/', ' ', $str);
    
    // if more than one hyphen then cut down to just one
    $str = preg_replace('/[-]{2,}/','-',$str);
    
    // make sure everything is lowercase
    $str = strtolower($str);
    
    return $str;
}

So the url ends up like this:

?name=http-www-guardian-co-uk-politics-2011-jun-13-nhs-reform-andrew-lansley&id=16

Fine,

However I was checking $_GET[‘name’] on page generation to make sure it existed in the database, throwing a 404 if it did not:

if (isset($_GET['name'])) {

    $sql = "SELECT title FROM content WHERE title = '" . (string)$_GET['name'] . "'";

    $node_title = $db->fetch_obj($sql);

    if ($node_title || ctype_digit($node_title)) {

        echo $node_title->title . ' / ' . $title;

    } else {

        header('HTTP/1.0 404 Not Found');
        header('Status: 404 Not Found');
        $page = 'inc/notfound.inc.php';
    }


}

But of course it doesn’t exist in the database because I’ve just used the safe_url() function to alter it… I need a new method for producing 404s if the wrong URL is typed in…

You need to store that URL string in the DB when the article is created, then search against that in your query.