Last Updated: February 25, 2016
·
2.504K
· etienne

SEO Friendly URLs with a Zend Filter

oddly enough i couldn't find a proper filter which handled special characters transliteration and multiple spaces, so i wrote this some time ago.

class My_Filter_SEOfriendly implements Zend_Filter_Interface
{   
    /**
         * @var string $separator 
         */ 
    private $separator;

    /**
         * @param string $separator 
         */
    public function __construct($separator = "-")
    {
        $this->separator = $separator;
    }

    /**
         * transliterates and slugifies
         * note: please provide UTF-8 input, otherwise iconv() will trigger a notice
         *
         * @param string $value
         * @return string
         */
    public function filter($value)
    {
        $value = strtolower($value);

        if (function_exists('iconv')) {
            $value = iconv('UTF-8', 'ASCII//TRANSLIT', $value);
        }

        $value = preg_replace("/[^[a-z0-9]+/", ' ', $value);
        $value = trim($value);
        $value = preg_replace("/[\s]/", $this->separator, $value);

        return $value;
    }       
}

it's a bit outdated and rough, but will do the job. I'll try port it to ZF2 soon.

[UPDATE 11/2012]
it looks like a full fledged filter will be included in 2.1 release of zend framework: https://github.com/zendframework/zf2/pull/2190

[UPDATE 05/2013]
That PR didn't make into ZF2 master but the filter is available in this module: https://github.com/Bacon/BaconStringUtils