Thursday 21 April 2016

PHP function to get source of webpage

Simple php function to get and display source code of a webpage.
function getSourceCode($pageurl) {
     $lines = file($pageurl);
     $output = "";
     foreach ($lines as $line_num => $line) {
         // loop thru each line and prepend line numbers
         $output.= "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br>\n";
     }
}

Wednesday 20 April 2016

Php function to validate email address

PHP function to validate Email Address 

Simple php function to validate email address. Helps in validating email address in php.

function isValidEmail($email) {
    if(preg_match("/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/", $email) > 0)
        return true;
    else
        return false;
}

Monday 18 April 2016

PHP function to convert Multidimensional Arrays to stdClass Objects

PHP function to convert Multidimensional Arrays to stdClass Objects

<?php
    function array2object($myarray) {
        if (is_array($myarray)) {
            return (object) array_map(__FUNCTION__, $myarray);
        }
        else {
            return $myarray;
        }
    }
?>

PHP function to convert stdClass Objects to Multidimensional Arrays

PHP function to convert stdClass Objects to Multidimensional Arrays

<?php
    function object2array($myobj) {
        if (is_object($myobj)) {
            $myobj = get_object_vars($myobj);
        }
        if (is_array($myobj)) {
            return array_map(__FUNCTION__, $myobj);
        }
        else {
            return $myobj;
        }
    }
?>

Friday 15 April 2016

PHP Predefined Constants

PHP Predefined Constants

Php in default has some predefined constants. This post explains about some major PHP magic constants.

  • __DIR__ – The directory of the file.
  • __FILE__ – The full path and filename of the file.
  • __CLASS__ – The class name.
  • __FUNCTION__ – The function name.
  • __METHOD__ – The class method name.
  • __LINE__ – The current line number of the file.
  • __NAMESPACE__ – The name of the current namespace

Tuesday 12 April 2016

Add PHP ordinal suffix to Numbers

Add PHP ordinal suffix to Numbers

Function to add st, nd, rd and th to numbers in php

function numberSuffix($number) {
        if(!in_array(($number % 100),array(11,12,13))) {
            switch ($number % 10) {
              case 1: return $number.'st';
              case 2: return $number.'nd';
              case 3: return $number.'rd';
            }
        }
        return $number.'th';
}

Thursday 7 April 2016

Right and Left Trim in php

Right and Left Trim in php

Right Trim:

To right trim a string use "rtrim" function in php
$path = "/test-string/"
echo $path = rtrim($path,"/"); 

Output:
/test-string


Left Trim:

To left trim a string use "ltrim" function in php
$path = "/test-string/"
echo $path = ltrim($path,"/"); 

Output:
test-string/