Archive for June, 2009

String to integer (strip all non numerics) with PHP

I’ve been hacking somebody else’s CMS (without access to the main engine) and needed to calculate a mathematical function on some prices. Specifically needed to display a percentage drop when given an original price as well as the current price. Here follows the journey. [Jump to The Solution.]

Easy right?

<?php
if($originalPrice > 0) {
	$percentageDrop = intval(100*(($originalPrice - $currentPrice)/$originalPrice));
}
?>

There was a Problem. The prices are stored not as integers but as formatted currency; ie “€ 120,000″

OK – easy – I found a simple solution to strip non alphanumerics (and space) and adapted it slightly:

<?php
function numericFromString( $string )
{
	return preg_replace('/[^0-9]/', '', $string);
}
?>

This function is then applied like so:
$currentPrice = numericFromString( ' € 120,000 ' ) ;

Worked in principle but not in practice – numbers seemed to balloon in size. [I didn't spot it all the numbers which had '8364' at the beginning...]

I had to call in Dave “tech support” Watson. “Bingo!” he said.

The problem [you've figured it out already... ] is that the euro symbol is a numeric HTML entity: &#8364;. There’s a bunch of numbers in there too. In fact – 8364.

Pendejo.

So Dave took my adapted [and useless] function and made it work. Now it looks like this:

The Solution

<?php
function numericFromString($string) {
	$string = str_replace('&#8364;','',$string);
	return preg_replace('/[^0-9]/','', html_entity_decode($string));
	}
?>

Why the extra line with str_replace? Because html_entity_decode doesn’t actually decode numerical html entities…

Would you believe it?

For more bullet proof results it may be worthwhile to try the following in place of that str_replace (from the comments at the official PHP manual at php.net)

$string = preg_replace('/&#(\d+);/me',"chr(\\1)",$string); //decimal notation
$string = preg_replace('/&#x([a-f0-9]+);/mei',"chr(0x\\1)",$string);  //hex notation

, ,

No Comments

Keeping your sites optimised

The sites I’ve been working on had been suffering from flab. A JavaScript library here (jQuery of course), a plug-in there, another, another, another… then a large plug-in that loads it’s own plug-ins (Shadowbox v3 – I’m talking to you).

It took a kick form outside to realise things were going downhill.

So – with the help of the good folk at Yahoo YSlow and the new copy-cat-kid on the block (Google Page Speed) with their plug-ins for a plug-in(firebug) for Firefox [oh the irony]… I’ve started to get things in line again.

Both YSlow and Page Speed have helpful links and information once called – and now I can pat myself on the back for having improved my YSlow scores from an ‘F’ to a ‘B’. Wetware heh.

Main issues I was able were too fix were too many HTTP requests and a lack of explicit caching direction from the web server. Nextly I’ll be looking at getting interface elements into a sprites for future jobs. (Must take this sprite/CSS creation tool for a spin. Looks absolutely fab.)

Reduce HTTP requests

While combining CSS files is trivial, combining a bunch of disparate JS files into one is not painless – I’ve had to drop a jQuery tooltip plug-in as it wouldn’t play nice when bundled up with its playground compatriots.

Server side caching and compression

is achieved the following htaccess rules:

##Cacheing static components

FileETag none
Header unset Etag

# Far future 1 YEAR
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf|mp3|mp4|css|js)$">
Header set Expires "Thu, 15 Apr 2010 20:00:00 GMT"
</FilesMatch>
<FilesMatch "scripts.inc.php$">
Header set Expires "Thu, 15 Apr 2010 20:00:00 GMT"
</FilesMatch>

# Past last modified
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf|mp3|mp4|css|js)$">
Header set last-modified "Sun, 13 Jul 2008 20:00:00 GMT"
</FilesMatch>
<FilesMatch "scripts.inc.php$">
Header set last-modified "Sun, 13 Jul 2008 20:00:00 GMT"
</FilesMatch>

#Compress
<IfModule mod_deflate.c>
<FilesMatch "\.(js|css)$">
SetOutputFilter DEFLATE
</FilesMatch>
</IfModule>

Shadowbox woes

I now may be on the lookout for a replacement to Shadowbox. Shadowbow v2 was great – it came with lots of build options and could be explicitly launched by jQuery on Document Ready. v2 wasn’t IE8 compatible however – forcing an upgrade to v3 – still in beta… Ho hum. This required an updated version of the JW FLV media player which I’m not mad keen on – and that needs a new licence. While Shadowbox is now very clever and can automatically find it’s own dependencies – it has many of these – each one with an HTTP request. While it is easy to combine the whole bundle into a single file its something I’d rather not have to do/keep track of – I’ve already got a rod for my back with the other jQuery plugins…

, , , , ,

No Comments

Wednesday fun #2

No Comments

Display proper maintenance page with .htaccess

Create a decent “sorry this site is down for maintenace” page with a “have a Nice day” message then when you do need to upgrade things use the following htaccess rewrite rule to forward all traffic to this page.

Adapted from Marco’s Webdev Notepad

RewriteEngine on
RewriteCond %{REMOTE_ADDR} !^83\.57\.178\.37$
RewriteRule !maintenance/index.html /maintenance/index.html [L,NC,R=302]

From Ask Apache (I like)

ErrorDocument 403 http://www.sub.domain.com/
Order deny,allow
Deny from all
Allow from 83.57.178.37

, , ,

No Comments

MAMP stacked (Mac OS X 10.5)

UPDATE: I’ve upgraded to Snow Leopard (Mac OS X 10.6) and the following instructions are no longer entirely valid as Marc Liyanage’s PHP package hasn’t been upgraded to work in the Snow.

Want to get MAMP on Mac OS X 10.6?

If you’re on 10.5 you may read on…

Want to roll a MAMP stack of your own to enable proper local web development? Try these steps to getting you own development environment:

1. Swap the Apple package of PHP for Marc Liyanage’s package of PHP for Mac OS X. Read his notes – only takes a minute. His version has useful “extras” like the mcrypt extension that Apple doesn’t include: you’ll want that for phpMyAdmin. (If you’ve already started Apple’s version – you’ll know how to stop it by re-commenting the LoadModule php5_module line in your http.conf file )

2. Get yourself virtualhost.sh from Patrick Gibson. This little shell script will make the process of setting up proper virtual domains on your development server a cinch. I use “.dev” or “.live” as the TLD to prevent any conflict with the live sites. (Although now I’ve started using Git I may just drop the separation between live and development branch domains on my development box. I still put all my sites in my ~/Sites folder though.

3. Get a Mac OS X MySQL package – (not the latest build but v5.0.x) from the good folks at MySQL. If you’ve already got another version installed – here’s how to uninstal MySQL from a Mac (NB – this will delete your databases too!).

4. Give your MySQL root user a password; type the following into the Terminal:
/usr/local/mysql/bin/mysqladmin -u root password sniggle
…if you like sniggle as a passowrd that is.

5. Now you can administer your MySQL server with phpMyAdmin and the root user you’ve just defined.  (There are other tools too – eg MySQL Administrator – but I’m used to phpMyAdmin from the hosting packeges I use). You may want to virtualhost phpMyAdmin to, for example, “http://mysql/”. Love virtualhost.sh.

6. Then for each [dynamic] site you’ll probably want to add a user and then associate a DB with that user. Do this in phpMyAdmin in one step using the Privileges pane fill in “Add a new User”/then select “Create database with same name and grant all privileges”. Job’s a good ‘un.

Done and not long-winded at-all at-all!

[Originally posted as a reply in Panic's Coda forum... Lots of love for MAMP Pro - a serious contender - and for just 40€... ]

, , , , , , , ,

No Comments