hairynuggets
hairynuggets

Reputation: 3311

PHP - How can I replace dashes with spaces?

I am currently using the following code to convert my strings to seo friendly urls:

        function url($url) {
    $url = str_replace(" ", " ", $url);
    $url = str_replace(array("'", "-"), "", $url); 
    $url = mb_convert_case($url, MB_CASE_LOWER, "UTF-8");
    $url = preg_replace("#[^a-zA-Z]+#", "-", $url); 
    $url = preg_replace("#(-){2,}#", "$1", $url); 
    $url = trim($url, "-"); 
        return $url;
} 

When I query my database I match the url against the article titles in my database, my problem is that after performing the seo friendly url function the urls do not match any article titles in my database.

The addition of dashes (not sure about the lowercase) means that they are completely different to the entries in the database.

What is my next step, should I remove the dashes before querying the database, if so how?

Or is it better practice to include the article id in my url somewhere and reference it?

Upvotes: 0

Views: 289

Answers (1)

maressyl
maressyl

Reputation: 983

Querying by id seems far faster and simplier to me than reconverting back your titles, using url rerwriting to ignore the title (just for referencement) and call a page with the id as a GET argument. Looking at the current URL let me think that StackOverflow works this way.

Using the current page as an example, i suspect that

http://stackoverflow.com/questions/8034788/php-how-can-i-replace-dashes-with-spaces

is rewritten to something like

http://stackoverflow.com/questions.php?id=8034788

where a simple SQL query gets the content of the article.

Upvotes: 2

Related Questions