JavaScript Editor Ajax software     Free javascripts 



Main Page

Figure 3-15
Congratulations! You’ve just implemented a very organized and powerful strategy that you can use to
rewrite all the URLs in your catalog, and you’ve also implemented the URL rewriting scheme that makes
them work.
Let’s analyze the code you’ve written piece by piece, starting with the
_prepare_url_text()
function.
This function prepares a string such as a product name or a category name to be included into a URL,
by either deleting or changing to dashes those characters in a string that are invalid or not aesthetically
pleasing in a URL. It retains all alphanumeric characters as-is. For example, if the function receives as a
parameter the string “Friends’ Shed”, it will return “Friends-Shed.”
The
_prepare_url_text()
function starts by using
preg_replace()
to delete all characters that aren’t
alphanumerical, a dash, a space, or an underscore, ensuring there are no characters left that could break
your URL:
// remove all characters that aren’t a-z, 0-9, dash, underscore or space
$NOT_acceptable_characters_regex = ‘#[^-a-zA-Z0-9_ ]#‘;
$string = preg_replace($NOT_acceptable_characters_regex, ‘’, $string);
The
preg_replace()
PHP function allows for string manipulation using regular expressions. The origi-
nal string is supplied as the third parameter. The function replaces the string portions matched by the
regular expression supplied as the first parameter, with the string supplied as the second parameter.
In this case, the regular expression
[^-a-zA-Z0-9_ ]
matches all characters not (
^
) in the set of letters,
numbers, dashes, underscores, or spaces. You indicate that the matching characters should be replaced
with
‘’
, the empty string, effectively removing them. The pound (
#
) character used to enclose the regu-
lar expression is the delimiter character that you need to use with regular expressions in PHP functions.
Then you continue by removing the leading and trailing spaces from the string it receives as parameter,
using the PHP
trim()
function:
// remove all leading and trailing spaces
$string = trim($string);
70
Chapter 3: Provocative SE-Friendly URLs
c03.qxd:c03 10:39 70


JavaScript Editor Ajax software     Free javascripts 
R7