I am trying to turn a standard wordpress title into a slug, that makes all characters lowercase, replaces spaces with dashes, and removes all “&” symbols that are in the titles.
So lets use this title as an example: “Identity & Wayfinding“
Here is my PHP:
<?php
$title = get_the_title();
$lower = strtolower($title);
$noDash = str_replace(' ', '-', $lower);
$noAnd = str_replace('&', '', $noDash);
echo $noAnd;
?>
This turns my title into “identity-#038;-wayfinding“
The lowercase conversion worked, but the replacing of the”&” with nothing isnot working . It is converting the “&” into an HTML special character. Any idea how I can simply replace the “&” with a blank, but also REMOVE the dash after that so the final title would be: “identity-wayfinding”?
If you want a slug, there are plenty of utilities which will do it for you, but neither htmlentities or urlencode is correct. Doctrine 1.2 included a
urlizerclass with a set of static functions includingurilizewhich will accomplish the behavior you desire in a more robust manner (handles UTF-8 and unaccenting correctly, etc.)It can be found here
If you want something less robust but far simpler:
That’ll strip non-alphanumeric characters (but also accented characters) and make spaces, + signs, and hyphens into hyphens.