Magento string manipulation

6th February 2013

It sure came as a surprise to me that Magento had these pretty handy string manipulation function hidden into a helper named core/string.

Apart from having a lot of binary-safe and iconv functions that do the usual substr(), strlen(), etc. It also has powerful truncate(), str_split(), splitInjection() and splitWords() functions.

For your comfort I've made a little showcase of how these functions work an what their output is.

// truncate($string, $length = 80, $etc = '...', &$remainder = '', $breakWords = true)
$remainder = '';
$string = 'Vestibulum lobortis mattis massa. Fusce malesuada mauris -et purus interdum venenatis.';
echo Mage::helper('core/string')->truncate($string, 50, '...', $remainder, true);
// Vestibulum lobortis mattis massa. Fusce malesuada mauris et purus interdum venenatis. Aliquam er...
echo Mage::helper('core/string')->truncate($string, 50, '...', $remainder, false);
// Vestibulum lobortis mattis massa. Fusce malesuada mauris et purus interdum venenatis. Aliquam...
echo $remainder;
// malesuada mauris et purus interdum venenatis.
// splitInjection($str, $length = 50, $needle = '-', $insert = ' ')
$string = 'ABCDEFGHIKJLMNOPQRSTUVWXYZ';
echo Mage::helper('core/string')->splitInjection($string, 5, 'G');
// ABCDE FG HIKJLMNO PQRST UVWXY Z
// splitWords($str, $uniqueOnly = false, $maxWordLength = 0, $wordSeparatorRegexp = '\s')
$string = 'I really really like turtles';
var_dump(Mage::helper('core/string')->splitWords($string));
/*
* array(5) {
*  [0]=>
*  string(1) "I"
*  [1]=>
*  string(6) "really"
*  [2]=>
*  string(6) "really"
*  [3]=>
*  string(4) "like"
*  [4]=>
*  string(7) "turtles"
*  }
*/
var_dump(Mage::helper('core/string')->splitWords($string, true));
/*
* array(4) {
*  ["I"]=>
*  string(1) "I"
*  ["really"]=>
*  string(6) "really"
*  ["like"]=>
*  string(4) "like"
*  ["turtles"]=>
*  string(7) "turtles"
*  }
*/

comments powered by Disqus