Wednesday, October 23, 2013

Helpful PHP functions you may not have heard of: Part 1

I'm always looking for a way NOT to reinvent the wheel, unless I have an abundance of available and a better design. While I often have a better design (shameless self promotion), I rarely have an abundance of time, which is why I love finding functions to make my life easier.

Check out the following 2 functions in php:

1. Parse the currency code and price as float from a string - numfmt_parse_currency
numfmt_parse_currency sample
$fmt = numfmt_create('en_US',NumberFormatter::CURRENCY);
$num = "$223.45";
$price_as_float = numfmt_parse_currency(
print $price_as_float . "\n"; //prints 233.45
print $curr . "\n"; //prints USD

2. Truncate text and add ... - mb_strimwidth
WARNING: Be careful using this function with text that has html in it! It may possibly break an html tag causing your entire page to show up blank!!
NOTE: the '...' gets included in the total length of the string
mb_strimwidth sample 1 - Truncate at end
$text = 'Some long text here!';
$trunc_text = mb_strimwidth($text, 0, 5);
print $trunc_text; //prints Some
$trunc_text = mb_strimwidth($text, 0, 5, '...');
print $trunc_text; //prints So...
mb_strimwidth sample 2 - Truncate at beginning
$text = 'Some long text here!';
$text_length = strlen($text);
$trunc_text = mb_strimwidth($text, 5, $text_length);
print $trunc_text; //prints long text here!
$trunc_text = '...'.mb_strimwidth($text, 5, $text_length);
print $trunc_text; //prints ...long text here!
mb_strimwidth sample 3 - Truncate at beginning and end
$text = 'Some long text here!';
$trunc_text = mb_strimwidth($text, 2, 8);
print $trunc_text; //prints me long
$trunc_text = '...'.mb_strimwidth($text, 2, 8, '...');
print $trunc_text; //prints lo...

I hope you found this post helpful. Play with the functions and share your own cool ways to use them!!

Please comment, share and follow!

See you next post ;)

No comments:

Post a Comment

Have a question? Something to add to the post? Do it here...