Custom PHP Functions: String functions
It's now time for some PHP that isn't Cake related. This is the first part in a series of "Basic/Common PHP functions that all programmers should know". This series has to deal with manipulating strings. I try to make my functions short, sweet and powerful, and I hope you learn something from them.
Truncate
This function takes a long string and shortens it to a defined length and adds appends an ellipsis (or custom string) to the end. Instead of chopping a word in half (if the limit finished within it), it moves the pointer up to the previous space.
/**
* Truncates a string to a certain length.
*
* @param string $text
* @param int $limit
* @param string $ending
* @return string
*/
public function truncate($text, $limit = 25, $ending = '...') {
if (strlen($text) > $limit) {
$text = strip_tags($text);
$text = substr($text, 0, $limit);
$text = substr($text, 0, -(strlen(strrchr($text, ' '))));
$text = $text . $ending;
}
return $text;
}
Shorten
This function works similarly to truncate(), but instead of chopping off the end of the string, it chops out the middle. This is useful for shortening users long names or websites.
/**
* If a string is too long, shorten it in the middle.
*
* @param string $text
* @param int $limit
* @return string
*/
public function shorten($text, $limit = 25) {
if (strlen($text) > $limit) {
$pre = substr($text, 0, ($limit / 2));
$suf = substr($text, -($limit / 2));
$text = $pre .' ... '. $suf;
}
return $text;
}
Obfuscate
Now this function doesn't directly scramble the text and confuse the user, instead it scrambles the source code. This is useful for displaying emails or other strings that you don't want to show up directly in your source code.
/**
* Scrambles the source of a string.
*
* @param string $text
* @return string
*/
public function obfuscate($text) {
$length = strlen($text);
$scrambled = '';
for ($i = 0; $i < $length; ++$i) {
$scrambled .= '' . ord(substr($text, $i, 1)) . ';';
}
return $scrambled;
}
Slugify
This function takes a string and makes it SEO and URL friendly (for example in the address bar for my blog posts). It lowercase's all words, replaces spaces with a dash, removes foreign/illegal characters and follows the guidelines for the best possible SEO. For example "Hello, my name is Miles Johnson!" would convert to "hello-my-name-is-miles-johnson".
/**
* Rewrite strings to be URL/SEO friendly.
*
* @param string $text
* @return string
*/
public function slugify($text) {
$text = trim(strtolower($text));
$text = str_replace(array('-', ' ', '&'), array('_', '-', 'and'), $text);
$text = preg_replace('/[^a-zA-Z0-9\-_]/is', '', $text);
$text = urlencode($text);
return $text;
}
Listing
This final function takes an array of items and turns them into an ordered list with the last item having the word "and" in front of it instead of a comma. Very good for making lists.
/**
* Creates a comma separated list with the last item having an "and".
*
* @param array $items
* @param string $and
* @return string
*/
public function listing($items, $and = 'and') {
if (is_array($items)) {
$lastItem = array_pop($items);
$items = implode(', ', $items);
$items = $items .' '. $and .' '. $lastItem;
}
return $items;
}
Now that's all I have for now, and I know you will use this in your code constantly just like I do! Be patient for my next series which will be dealing with basic date/time functions.
18 Comments
For the first scenario you could add a check for the presence of spaces in the limited string. For the second scenario you could add a check if a space is present directly behind the limit.
Why not use the strtr function in the slugify function, it's faster, and then you don't have to use the array_keys and array_values functions. The reworked function.
@Wittedruif - I think the problem is my blog post is not displaying the characters correctly, the ? should be a character not a ?. I think ill upload a file somewhere to download the correct one.
I got the same error as Lee. Turns out its a regular expression error. The question marks in the map are not escaped and breaks down the expression.
Change '/è|é|ê|?|ë/' => 'e',
to '/è|é|ê|\?|ë/' => 'e',
Change '/ù|ú|?|û/' => 'u',
to '/ù|ú|\?|û/' => 'u',
And that makes it work for me.
Bookmarked!
It is most likely caused from the $map variable. You need to be saving your php/files as UTF-8 so that those special characters aren't encoded incorrectly. If that doesn't work, comment out the $map variable and the first preg_replace().
Warning: preg_replace() [function.preg-replace]: Compilation failed: nothing to repeat at offset 6 in friendly_urls.php on line 28
There's one thing I want to mention. I'm Czech and Czech alphabet isn't really URL-friendly. Therefore I have to use some sort of "slugify" function. My favourite choice is friendly_url by Jakub Vrána (http://php.vrana.cz/vytvoreni-pratelskeho-url.php) using iconv. Although I must admit there can be problems with implementation of iconv library and its different versions. Anyway this function can be used as an alternative to the one you created.