Custom Web Applications to Grow Your Business

(256) 429-8145

Create clean seo friendly urls in cakephp beforeSave function

A neat trick in creating seo friendly url in cakephp is to just create a few lines of regex code to clean the data before it is saved. However, you want to perform this task only when you are adding new articles NOT on edit

public function beforeSave($options = array()) {
		// perform only on add, not edit, thus a check for primary key
		if (!$this->id && !isset($this->data[$this->alias][$this->primaryKey])) { 
		    // remove url characters
			$url = iconv('UTF-8', 'ASCII//TRANSLIT', $this->data[$this->alias]['title']);
			$url = trim($url);
			$url = preg_replace("/[^a-zA-Z0-9\/_| -]/", '', $url);
			$url = strtolower(trim($url, '-'));
			$url = preg_replace("/[\/_| -]+/", '-', $url);
			$url = trim($url);
			$this->data[$this->alias]['title_slug'] = $url;
		return true;