Martin AJ Martin AJ - 1 year ago 98
PHP Question

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:

automatically it will be replaced with this:

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
with title-part of the
. How can I determine "title-part"? It is everything which is after
(end of string). How can I do that comparison?

And then:

if ( preg_match("//", $current_uri) ) {
// all fine. continue loading the page
} 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);

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download