The function below will show you how to make a search engine optimised slug for a category or post title with the same output that you will get from WordPress' sanitize_title_with_dashes function.
All three functions are required.
1
<?php
2
/*
3
Sanitise name for safe URL
4
Source: http://codex.wordpress.org/Function_Reference/sanitize_title_with_dashes
5
Usage: sanitize_title_with_dashes();
6
http://www.beliefmedia.com/code/php-snippets/post-slugs
7
*/
8
9
10
11
// Preserve escaped octets.
12
13
// Remove percent signs that are not part of an octet.
14
15
// Restore octets.
16
17
18
19
20
21
}
22
23
}
24
25
26
27
28
29
if ( 'save' == $context ) {
30
// Convert nbsp, ndash and mdash to hyphens
31
32
33
// Strip these characters entirely
34
35
// iexcl and iquest
36
'%c2%a1', '%c2%bf',
37
// angle quotes
38
'%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
39
// curly quotes
40
'%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
41
'%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
42
// copy, reg, deg, hellip and trade
43
'%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
44
// acute accents
45
'%c2%b4', '%cb%8a', '%cc%81', '%cd%81',
46
// grave accent, macron, caron
47
'%cc%80', '%cc%84', '%cc%8c',
48
), '', $title );
49
50
// Convert times to x
51
52
}
53
54
55
56
57
58
59
return $title;
60
}
1
<?php
2
/*
3
Sanitise name for safe URL
4
Source: http://codex.wordpress.org/Function_Reference/sanitize_title_with_dashes
5
Usage: sanitize_title_with_dashes();
6
http://www.beliefmedia.com/code/php-snippets/post-slugs
7
*/
8
9
10
11
for ($i=0; $i < $length; $i++) {
12
13
if ($c < 0x80) $n = 0; # 0bbbbbbb
14
elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
15
elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
16
elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
17
elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
18
elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
19
else return false; # Does not match any model
20
for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
21
22
return false;
23
}
24
}
25
return true;
26
}
1
<?php
2
/*
3
Sanitise name for safe URL
4
Source: http://codex.wordpress.org/Function_Reference/sanitize_title_with_dashes
5
Usage: sanitize_title_with_dashes();
6
http://www.beliefmedia.com/code/php-snippets/post-slugs
7
*/
8
9
10
$unicode = '';
11
$values = array();
12
$num_octets = 1;
13
$unicode_length = 0;
14
15
16
for ($i = 0; $i < $string_length; $i++ ) {
17
18
19
20
if ( $value < 128 ) {
21
if ( $length && ( $unicode_length >= $length ) )
22
break;
23
24
$unicode_length++;
25
} else {
26
27
28
$values[] = $value;
29
30
if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
31
break;
32
33
if ($num_octets == 3) {
34
35
$unicode_length += 9;
36
} else {
37
38
$unicode_length += 6;
39
}
40
41
$values = array();
42
$num_octets = 1;
43
}
44
}
45
}
46
47
return $unicode;
48
}
49
?>
Usage
Returns: this-is-a-cool-title
.