Martin AJ
Martin AJ

Reputation: 6697

How can I check the post slug?

Scenario: As you know, StackOverflow checks the title in the question. I mean when you open this URL:

http://stackoverflow.com/questions/38839016/should-i-store-the-result-of-an-function

automatically it will be replaced with this:

http://stackoverflow.com/questions/38839016/should-i-store-the-result-of-an-function-into-an-array

That replacement is because of being incomplete the first URL.


Ok well, I'm trying to make such a system by PHP. Here is my attempt:

// getting this from the URL
$id = '38839016';

// fetching this from database based on that id (38839016)
$real_title = $result['title'];
//=> Should I store the result of an function into an array
$real_title = str_replace("-"," ",strtolower($real_title));
//=> should-i-store-the-result-of-an-function-into-an-array

// getting whole uri                                
$current_uri = $_SERVER["REQUEST_URI"];
//=> /questions/38839016/should-i-store-the-result-of-an-function

What I want to do: I need to compare $real_title with title-part of the $current_uri. How can I determine "title-part"? It is everything which is after $id.'/' until / or ? or $ (end of string). How can I do that comparison?

And then:

if ( preg_match("//", $current_uri) ) {
    // all fine. continue loading the page
    continue;
} else {
    // replace title-part of the $current_uri with $real_title       
    preg_replace("//", $real_title, $current_uri);         

    // redirect to this post with correct slug
    header('Location: '.$_SERVER["HTTP_HOST"].);
}

briefly, I want to complete these:

if ( preg_match("//", $current_uri) ) {

preg_replace("//", $real_title, $current_uri); 

Upvotes: 0

Views: 268

Answers (1)

Mostafa
Mostafa

Reputation: 909

Ok, in simple words, there is a good url and a requested url

if the requested url not equal the good url

redirect the visitor to the good one

<?
$id = '38839016';
$good_url = '/questions/'.$id.'/'.str_replace("-"," ",strtolower($result['title']));

preg_match( '/\/[0-9]+\/([a-z0-9-]+)\/.*/', $_SERVER[REQUEST_URI], $matches);
if ($matches[1] != str_replace("-"," ",strtolower($result['title'])))
header('Location: '.$good_url);

Upvotes: 1

Related Questions