PHP String Functions (Starts With, Ends With, Length, Sub String, Remove Html, Replace, Contains, Is Valid Email, Is Empty Or Null)

12/1/2013 5:54:24 PM

Coming from a .NET background, I wanted to create a set of easily used PHP string functions similar to those I use in .NET. The following class encapsulates many common string functions that I use.

  • Starts With - does string start with searched value
  • Ends With - does string end with searched value
  • Length - get length of string
  • Sub String - get a sub string
  • Replace - replace a value in a string with a new value
  • Contains - check if a string contains a value
  • Is Empty Or Null - check if a string is either empty or null
  • Empty And Trim - sets a null string to an empty string and trims trailing spaces from a non-null string
  • Is Valid Email - check if a string is a valid email
  • Remove Html - remove html characters from a string
  • Get Extension - gets the extensions of a filename represented as a string
  • JSON Encode - encode an object into its JSON string representation
  • JSON Decode - decodes a JSON encoded string into an object
  • Hash String - Hash a string
  • Random String - Get a random alpha numeric string
  • Get Guid String - Get a new Guid value as a string
class StringFunctions
{

    static function StartsWith($value, $searchedValue)
    {
        return !strncmp($value, $searchedValue, strlen($searchedValue));
    }


    static function EndsWith($value, $searchedValue)
    {
        $length = strlen($searchedValue);
        if ($length == 0)
        {
            return true;
        }

        return (substr($value, -$length) === $searchedValue);
    }


    static function Length($source)
    {
        if (self::EmptyAndTrim($source) == false)
        {
            return strlen($source);
        }

        return 0;
    }


    static function SubString($source, $startIndex, $length)
    {
        if (self::IsEmptyOrNull($source) == false)
        {
            //this only works for index == 0
            if (self::Length($source) < $length)
            {
                $length == self::Length($source);
            }

            return substr($source, $startIndex, $length);
        }

        return $source;
    }


    static function RemoveHtml($source, $keepLineBreaks = true)
    {
        $source = self::EmptyAndTrim($source);
        if (self::IsEmptyOrNull($source) == false)
        {
            $allowableTags = "";

            if ($keepLineBreaks == true)
            {
                $allowableTags = "<p><br>";
            }

            $source = strip_tags($source, $allowableTags);

            if ($keepLineBreaks == true)
            {
                //remove beginning <p>
                $source = self::Replace($source, "<p>", "");

                //replace </p>, <br>, <br/>, <br /> with new line
                $source = self::Replace($source, "</p>", "\r\n");
                $source = self::Replace($source, "<br>", "\r\n");
                $source = self::Replace($source, "<br/>", "\r\n");
                $source = self::Replace($source, "<br />", "\r\n");
            }
        }

        return $source;
    }


    static function Replace($source, $searchPhrase, $replacementValue)
    {
        $source = self::EmptyAndTrim($source);
        return str_replace ($searchPhrase, $replacementValue, $source);
    }


    static function Contains($string, $substring)
    {
        $pos = strpos($string, $substring);
        if ($pos === false)
        {
            // string needle NOT found in haystack
            return false;
        }
        else
        {
            // string needle found in haystack
            return true;
        }
    }


    static function IsValidEmail($value)
    {
        if (self::isEmptyOrNull($value) == false)
        {
            if (filter_var($value, FILTER_VALIDATE_EMAIL))
            {
                return true;
            }
        }

        return false;
    }


    static function IsEmptyOrNull($str)
    {
        if ($str === null || $str == "")
        {
            return true;
        }
        return false;
    }


    static function EmptyAndTrim($str)
    {
        if (self::IsEmptyOrNull($str))
        {
            $str = "";
        }

        $str = trim($str);
        return $str;
    }

  
    static function GetExtension($str)
    {
        $i = strrpos($str,".");
        if (!$i)
        {
            return "";
        }
        $l = strlen($str) - $i;
        $ext = substr($str, $i+1, $l);

        return $ext;
    }


    static function JSONEncode($obj)
    {
        return json_encode($obj);
    }


    static function JSONDecode($str, $toArray)
    {
        return json_decode($str, $toArray);
    }


    static function HashString($str, $salt)
    {
        return hash('sha512', $str . $salt);
    }


    static function RandomString($length)
    {
        if ($length > 62)
        {
            $length = 62;
        }

        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

        return substr(str_shuffle($chars), 0, $length);
    }


    static function GetGuidString()
    {
        $guid = com_create_guid();
        $guid = str_replace("{", "", $guid);
        $guid = str_replace("}", "", $guid);

        return $guid;
    }
}