Extract email addresses from a string – PHP

Sometimes you need to extract multiple email addresses from a string and the following function will make all your dreams come true.

function extract_emails_from($string){
    preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $string, $matches);
    return $matches[0];
}

..and this is how you use it:

$text = "this is some text and here is an email address [email protected], here’s another [email protected], etc..";
$emails = extract_emails_from($text);

Now let’s use the data:

// as string
print(implode("\n", $emails));

// loop as array
foreach($emails as $email) {
    echo $email .",";
}

How to drive traffic to your website!

This is a very hot topic indeed.

Definitely one that everyone with a website should know all about.

 

To begin our journey we will look directly at the Traffic Generator Sites out there who – to be honest – are complete scams because all they really do is one of two things…

1.) Load your site into those annoying pop-under ad windows that users close immediately as they appear(not having opened them themselves)

2.) Use proxy scripts to load your website using many different IP addresses leading you to believe they are all “human visitors” when really all they are, are bots!!!

Bots” you ask, what are they?

Well, bots are computer programs that go to sites to retrieve content for some greater good. Automation at it’s finest.

e.g. Google and all the other search engines use “bots” to scrape/collect content off of websites in order for their search results to appear relevant to what your typed in keywords are.

Anyways, back on topic. These sites claim to bring thousands if not millions of users to your site for a set fee per user or some “deal” they make up on the spot which is as useless as anything could possibly be.

The conversion rates of anyone looking at your site through this method is very very low and therefore we will consider this technique useless and we will avoid it like the plague!

 

Moving onto the other really common one, Commenting on Sites.

Commenting on another site’s articles or blog posts can work quite well, but there’s a point when it just becomes spam!

It’s best to avoid this other than when you are actually doing it yourself, as there are programs out there which allow this to be automated and while this sounds like a good plan, Google doesn’t really like it and your site could suffer the consequences of “spamming your way to the top“.

This does help quite a bit for comments on sites that are relevant to what your site does as well. It sort of “links everything within a network” if you will. Forming allies and building relevant back-links as you go.

The conversion rates for this are alright, but more than bringing traffic, it’s more of a general back-link builder. So we will say use this at your own risk.

 

It feels like it’s time we should explore the Blogging and Article Writing method which is probably the best of all the options, it’s organic and makes you seem like you’re worth reading, well, at least to search engines!…

You should focus on a niche idea that you understand quite well and are interested in, because you will be spending a very long time on it. By long time I mean at least a few months if not years. It’s hard to become a brand that people remember and come back to, even harder to remain up there as other people and sites gain momentum and start taking your valuable readers and clients you’ve spent so long cultivating.

Once you have written some honest and concise posts (preferably two a week as you grow) expand on what you are feeding your users so that they keep wanting more and return to look for fresh content.

By now you will have a somewhat captive audience reading your every word, which means it’s time for you to identify your competition and start building those back-links with them and things they write (as per the “Commenting on Sites” section above).

Before you know it you will have a following and you can start monetizing the traffic you have brought to your site.

The conversion rates for this are pretty good and we recommend giving this one a whole lot of focus to get it right – it’s also probably the hardest one to get right!

 

Finally there is the Advertising route which works wonders but costs quite a bit, so if you are prepared to spend some cash, this one is a sure fine winner.

Before you start jumping for joy remember that there is no way people will stay on your site once they get there unless you have something that they want to see and come back for. This brings me back to what you’ve just read above, which we’ve termed as the “Blogging and Article Writing” section. Make sure to write great content or have some service to provide that is unique and refreshing!

Make sure you have decent content for people to look at otherwise you would have just spent money on advertising and the bounce rates will be so high you could write an article about that!

The conversion rates for this are also pretty good because usually the traffic you receive can be geographically controlled to users with specific demographics that are meaningful to your site.

jQuery limit fields to alphanumeric characters only

I was trying to restrict a form’s field from only allowing the user to enter alphanumeric characters into it. I looked all around and couldn’t find a nice way to do it without a plugin, so I wrote my own bind function that you can attach straight to an element.

$("#yourFieldsElementId").bind("keypress", function (event) {
    if (event.charCode!=0) {
        var regex = new RegExp("^[a-zA-Z0-9]+$");
        var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
        if (!regex.test(key)) {
            event.preventDefault();
            return false;
        }
    }
});

If you would like to restrict the input to only be numeric then do this:

$("#yourFieldsElementId").bind("keypress", function (event) {
    if (event.charCode!=0) {
        var regex = new RegExp("^[0-9]+$");
        var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
        if (!regex.test(key)) {
            event.preventDefault();
            return false;
        }
    }
});

If you would like to restrict the input to only be alphabetical then do this:

$("#yourFieldsElementId").bind("keypress", function (event) {
    if (event.charCode!=0) {
        var regex = new RegExp("^[a-zA-Z]+$");
        var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
        if (!regex.test(key)) {
            event.preventDefault();
            return false;
        }
    }
});

If you’re wondering about the following line:

if (event.charCode!=0) {

It is there to double check that if the delete or backspace key is pressed.
If you don’t have this check then you cannot delete data.

Make a dynamic year dropdown using PHP

Ever wanted to have a dropdown that automatically showed the current year and the few years before it?

This is a quick and easy way to do exactly that!

<select name="year">
    <?
    for($i=date("Y")-5;$i<=date("Y");$i++) {
        $sel = ($i == date(‘Y’)) ? ‘selected’ : ;
        echo "<option value=".$i." ".$sel.">".date("Y", mktime(0,0,0,0,1,$i))."</option>";
    }
    ?>
</select>

Pad a string with zeros using PHP

Recently I had to create a code/username maker to fit into a certain type of pattern so that all “broker codes” (as they were called) followed the same path.
An example one looked like so:

HJTH0001

The number needed to increment and I wanted to use the auto-increment feature in the mysql database table that was driving this data to make it.

This was easy but I ended up with a code that looked like this:

HJTH1

No zeros!

So I found a built in PHP function which I somehow managed to overlook for years and years and years.

The magic function this time around is called… str_pad() and I used it like this to get the result I was after:

$last_id = 1;
/*
$last_id is dynamically assigned from the mysql_insert_id() after the mysql_query() finishes, and we have a auto-increment value
*/

$brokercode = "HJTH".str_pad($last_id, 4, 0, STR_PAD_LEFT);

RuntimeError: thread.__init__() not called (Python)

Today I got a really dumb error from Python.

RuntimeError: thread.__init__() not called

But luckily it’s really easy to fix!

Below is the code before (with the error):

class SomeThread(Thread):
    def __init__(self, myVar):
        self.sMyVar = str(myVar)
    def run(self):
        self.sMyVar = "bla.." + self.sMyVar

And now for the code that resolved the problem:

class SomeThread(Thread):
    def __init__(self, myVar):
        Thread.__init__(self)
        self.sMyVar = str(myVar)
    def run(self):
        self.sMyVar = "bla.." + self.sMyVar

If you have really bad eye-sight and can’t spot the difference between the 2 code block above :P
What we do is add the following code in the beginning of the construct – or __init__ in Python:

Thread.__init__(self)

Also be aware that I originally did:

from threading import Thread

Which means I don’t have to instantiate it going forward using `threading.Thread`, instead I can do `Thread` alone.

Recursively Delete Files and Folders and all Contents using PHP

Below is a quick and easy way to recursively delete all files and folders in a given path using PHP.

<?php

    function destroy_dir($dir) {
        if (!is_dir($dir) || is_link($dir)) return unlink($dir);
        foreach (scandir($dir) as $file) {
            if ($file == "." || $file == "..") continue;
            if (!destroy_dir($dir."/".$file)) {
                chmod($dir."/".$file, 0777);
                if (!destroy_dir($dir."/".$file)) return false;
            };
        }
        return rmdir($dir);
    }

    destroy_dir("/var/www/site/public_html/directory/");

?>

Windows 7 is better than Ubuntu 12.04 on desktop!

Today we have finalised for ourselves that Windows 7 is definitely a “better” operating system than Ubuntu 12.04 when it comes to desktop environments.

Now, I say “better” in quotes because the word is quite hard to use as is and “convince” everybody while doing so.

We started our journey on Windows 7 and after desperately needing a reinstall we decided to go for the latest version (at the time) of Ubuntu, which happened to be the brand spanking new Ubuntu 12.04.

We went to the ubuntu site, found the ISO we needed, then started the download, for some reason the download was extremely slow so we found the torrent version of it instead and went for that, much better idea and it maxed out our internet connection until it was done a few moments later.

We then burnt the ISO to a disc so we could boot from it and have it accessible whenever we needed it.

This was the point where we were about to kiss the good old Windows 7 partition goodbye for good and move onto the apparent newer much “cooler” Ubuntu version.

The installation of Ubuntu 12.04 was really quick and simple and quite a pleasure really.

Finally we were booted up and ready to get our day-to-day software installed as well so we could do some work – boy was this a “wonderful experience” (I can hear you moaning about how if you know Linux then it’s quite easy and all round a lovely thing, and we don’t disagree, in fact we have Ubuntu Server Edition installed on most of our web servers and love it to bits, but as far as the desktop side of things is concerned..)

Things were alright for a few days, but not great as we all run multiple screens each in the office and this means getting the proper graphics card drivers installed on the systems. Not a massive problem, but not as easy as it’s meant to be, the support is somewhat limited.

We tried out a few 3d games to test the graphics performance differences between the operating systems and I must say, that was not a great experience either.

The overall feel of things was of a less quality and a much more “mission packed” than one would like and unless you are doing things like, well, who-knows really, then I’d say rather go the main-stream Windows route.

What was really nice to use was the built in command line and all the great things that come with Linux’s side of the fence, like SSH support off the bat for example, very nice!

We decided to remove the Ubuntu desktop partitions and replace them with fresh new copies of Windows 7 today and so far we feel like we’ve died and gone to heaven as there’s so much more that “just works” from the get go!

With all that said, I’m really looking forward to seeing where the next versions of Ubuntu go as there are some really nice things being implemented at the moment, for example the Unity navigational system which is a pleasure to use in it’s entirety.

Function split() is deprecated in PHP

You heard it right! split() is officially a deprecated function. That means that you can still use it if you are really brave and it will work correctly, but don’t expect to see it in later versions of PHP when they come out. Somewhere along the line it WILL not work at all.

It has been marked as “deprecated” due to the fact that the explode() function has the exact same output!

So just replace the word “split” with “explode” and you’ll be done.