Tagged as php

edit delete favorite
Posted by boxfan on Nov 10, 2007
Something often overlooked, but simple to write with regex would be username validation. For example, we may want our usernames to be between 4 and 28 characters in length, alpha-numeric, and allow underscores.
$string = "userNaME4234432_";
if (preg_match('/^[a-z\d_]{4,28}$/i', $string)) {
echo "example 1 successful.";
}
php
 
edit delete favorite
Posted by boxfan on Nov 10, 2007
Telephone Numbers - A much more interesting example would be matching telephone numbers (US/Canada.) We'll be expecting the number to be in the following form: (###)###-####

Again, whether the phone number is typed like (###) ###-####, or ###-###-#### it will validate successfully. There is also a little more leeway than specifically checking for enough numbers, because the groups of numbers can have or not have parenthesis, and be separated by a dash, period, or space.
$string = "(032)555-5555";
if (preg_match('/^(\(?[0-9]{3,3}\)?|[0-9]{3,3}[-. ]?)[ ][0-9]{3,3}[-. ]?[0-9]{4,4}$/', $string)) {
echo "example 2 successful.";
}
php
 
edit delete favorite
Posted by boxfan on Nov 10, 2007
Validate an email address
$string = "first.last@domain.co.uk";
if (preg_match(
'/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',
$string)) {
echo "example 3 successful.";
}
php
 
edit delete favorite
Posted by boxfan on Nov 10, 2007
$string = "255.255.255.0";
if (preg_match(
'^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$',
$string)) {
echo "example 5 successful.";
}
php
 
edit delete favorite
Posted by jimbojw on Nov 14, 2007
Simple PHP script to help you convert your files to either base64 or percent encoded strings. Presumably for use in Data URIs, or otherwise embedding image data directly in another file/format.
<?php
 
if ($_FILES && $_FILES['uploadfile']) {
    header( "Content-type: text/plain; charset=UTF-8" );
    $fp = fopen( $_FILES['uploadfile']['tmp_name'], 'rb' );
    if ($_POST['base64']) {
        while (!feof($fp)) echo(base64_encode(fread($fp, 45))."\n");
    } else {
        $buf = '';
        while (!feof($fp)) {
            $buf .= rawurlencode(fread($fp, 120));
            while (strlen($buf)>=60) {
                echo(substr($buf,0,60)."\n");
                $buf = substr($buf,60);
            }
        }
        if ($buf) echo($buf);
    }
    fclose($fp);
    die();
}
 
?>
<html>
<head>
<title>Base64 File Encoder</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<p><label>File to convert: <input type="file" name="uploadfile" /></label>
<p><label>Check here to use base64 encoding: <input type="checkbox" name="base64" checked="checked" /></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
</body>
</html>
 
Please submit any bugs/features and report abuse. Thanks!
Spacer
Spacer
Spacer
Top Users
Spacer
Top Tags
Spacer