Remove illegal characters from SEO links

ChrisTERiS
ChrisTERiS used Ask the Experts™
on
I'm using:
str_replace(" ", "-", $row['title']).'.html';

Open in new window

for building seo friendly urls, and it works fine. But there are some illegal characters eg % which are giving bad request.
Is there any function to remove all such illegal characters (I assume that there are other characters too).
I'm using PHP as server-side language.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Hello.
Why dont you try urlencode or htmlspecialchars or better yet a preg_replace?

Author

Commented:
Because I don't know which characters to add in the preg_replace.
Finally I build my own function:
function getSeoTitle($title) {
    $title = strip_tags($title);
    $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
    $title = str_replace('%', '', $title);
    $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
    $title = strtolower($title);
    $title = preg_replace('/&.+?;/', '', $title); // kill entities
    $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
    $title = preg_replace('/\s+/', '-', $title);
    $title = preg_replace('|-+|', '-', $title);
    $title = trim($title, '-');
    return $title;
}

Open in new window

Most Valuable Expert 2011
Top Expert 2016

Commented:
Next time you have a question for EE, please give us some test data to work with.  You'll get faster and better results, I promise.  This article explains a little bit of the "why."
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_7830-A-Quick-Tour-of-Test-Driven-Development.html

Author

Commented:
Because the other one was very generic.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial