Skip to content

Instantly share code, notes, and snippets.

Created Jun 11, 2012
Embed
What would you like to do?
php slugify string
<?php
function slugify($str) {
$search = array('Ș', 'Ț', 'ş', 'ţ', 'Ş', 'Ţ', 'ș', 'ț', 'î', 'â', 'ă', 'Î', 'Â', 'Ă', 'ë', 'Ë');
$replace = array('s', 't', 's', 't', 's', 't', 's', 't', 'i', 'a', 'a', 'i', 'a', 'a', 'e', 'E');
$str = str_ireplace($search, $replace, strtolower(trim($str)));
$str = preg_replace('/[^\w\d\-\ ]/', '', $str);
$str = str_replace(' ', '-', $str);
return preg_replace('/\-{2,}', '-', $str);
}
@tupakapoor

This comment has been minimized.

Copy link

@tupakapoor tupakapoor commented Feb 2, 2014

return preg_replace('/\-{2,}', '-', $str);
should be
return preg_replace('/\-{2,}/', '-', $str);
with the added slash at the end of the regex

@tmtinteractive

This comment has been minimized.

Copy link

@tmtinteractive tmtinteractive commented Jun 24, 2018

There's no No ending delimiter after value is returned

Corrected funtion

function slugify($str){
$search = array('Ș', 'Ț', 'ş', 'ţ', 'Ş', 'Ţ', 'ș', 'ț', 'î', 'â', 'ă', 'Î', 'Â', 'Ă', 'ë', 'Ë');
$replace = array('s', 't', 's', 't', 's', 't', 's', 't', 'i', 'a', 'a', 'i', 'a', 'a', 'e', 'E');
$str = str_ireplace($search, $replace, strtolower(trim($str)));
$str = preg_replace('/[^\w\d\-\ ]/', '', $str);
$str = str_replace(' ', '-', $str);
return preg_replace('/-{2,}/', '-', $str);
}

@junieldantas

This comment has been minimized.

Copy link

@junieldantas junieldantas commented Jul 8, 2019

Sugestion for remove end trace '-'

return (substr($str, -1) == '-' ? substr($str, 0, -1) : $str );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment