I am looking to solve a problem dealing with "pretty links" or "permalinks" that list the title of books, such as:
http://www.example.com/title/The-Catcher-in-the-Rye/
When I deal with regular book titles, such that have simple words or spaces, there is no problem, since I can simply replace the space with a dash -
and deal with finding the book title in the database by doing a reverse str_replace
.
However, the problem arises when I have titles of books that have either apostrophes '
or colons :
in them, or both as in this example:
Why Can't I Be You: A Novel
In my sql database, all single quotes are escaped, so that the entry in the database is as follows:
+-----+-------------------------------+
| BID | book_title |
+-----+-------------------------------+
| 1 | Why Can\'t I Be You: A Novel |
+-----+-------------------------------+
When I list all book titles, I again unescape the string, so it lists simply as: Why Can't I Be You: A Novel
My <a>
links show the unescaped title, with the pretty links created by replacing spaces with dashes and omitting the apostrophes and colons as follows:
<a href="http://www.example.com/title/why-cant-i-be-you-a-novel" title="Why Can't I Be You: A Novel">Why Can't I Be You: A Novel</a>
So, getting to my problem. I want to be able to list all the titles of the books formatted (unescaped) and have the "permalinks" / "pretty links" with hyphens work and return the proper title to the GET method.
In my .htaccess
entry, I have the following RewriteRule
:
RewriteRule ^title/(.*[^/])/?$ viewbook.php?booktitle=$1 [NC,L]
What this does is take the "pretty" link portion that follows title/
and sends it via GET to viewbook.php
. So for example for the book The Catcher in the Rye, the following is sent via GET: The-Catcher-in-the-Rye
No problem there, since it is simple in php to resolve this issue:
$booktitle = $_GET['booktitle'];
$goodBookTitle = str_replace('-', ' ', $booktitle);
// or we can do it all at once
$booktitle = str_replace('-', ' ', $_GET['booktitle']);
// Send $booktitle to SQL query and find the book
This works fine when no apostrophes are found, however, this method does not help if the title has either apostrophes or colons since it will not be found in the database. I also do not want to use the WHERE book_title LIKE '%$booktitle%'
since viewbook.php
has to be the exact match.
I am looking for an elegant or simple solution which will enable me to solve this via a RewriteRule
and not have to add extra tables to the database for say slug
or permalink
, and I don't want to have apostrophes in the url such as %27 for single quote. This is a large database on which data entry is done in a spreadsheet, exported to CSV and uploaded into the SQL database. There is no front end for individual entries to allow for such things as slug
or equivalent.
I hope my explanation is clear.