Categorygithub.com/gouniverse/php
modulepackage
1.1.2
Repository: https://github.com/gouniverse/php.git
Documentation: pkg.go.dev

# README

PHP functions implemented by Golang

CI GoDoc codecov Release

This package implements some PHP functions by Golang. Please note that it's impossible to have 100% the same behaviour between PHP and Golang functions because their mechanisms are quite different.

Minimum go version requirement: 1.18, if you are using lower version, please choose version v0.62.

Date/Time Functions

PHP functionGolang function
checkdateCheckdate
dateDate
strtotimeStrtotime
timeTime
microtimeMicrotime
date_addDateAdd
date_create_from_formatDateCreateFromFormat
date_createDateCreate
date_date_setDateDateSet
date_default_timezone_getDateDefaultTimezoneGet
date_default_timezone_setDateDefaultTimezoneSet
date_diffDateDiff
date_formatDateFormat
date_interval_create_from_date_stringDateIntervalCreateFromDateString
date_isodate_setDateISODateSet
date_modifyDateModify
date_offset_getDateOffsetGet
date_subDateSub
date_timestamp_getDateTimestampGet
date_timestamp_setDateTimestampSet
date_timezone_getDateTimezoneGet
date_timezone_setDateTimezoneSet

String Functions

PHP functionGolang function
addslashesAddslashes
chrChr
crc32Crc32
explodeExplode
bin2hexBin2hex
hex2binHex2bin
htmlspecialcharsHTMLSpecialchars
htmlspecialchars_decodeHTMLSpecialcharsDecode
implodeImplode
str_ireplaceIreplace
lcfirstLcfirst
md5Md5
md5_fileMd5File
sha1Sha1
sha1_fileSha1File
number_formatNumberFormat
ordOrd
str_replaceReplace
similar_textSimilarText
stripslashesStripslashes
mb_striposStripos
mb_stristrStristr
mb_strlenStrlen
mb_strposStrpos
mb_strriposStrripos
mb_strrposStrrpos
mb_strstrStrstr
mb_substrSubstr
str_padStrPad
str_repeatStrRepeat
strrevStrrev
strtolowerStrtolower
strtoupperStrtoupper
str_word_countStrWordCount
ltrimLtrim
rtrimRtrim
trimTrim
ucfirstUcfirst
ucwordsUcwords

Math Functions

PHP functionGolang function
absAbs
base_convertBaseConvert
bindecBindec
decbinDecbin
dechexDechex
hexdecHexdec
decoctDecoct
octdecOctdec
ceilCeil
floorFloor
piPi
mt_randMtRand
randRand
roundRound

Array Functions

PHP functionGolang function
array_chunkArrayChunk
array_columnArrayColumn
array_combineArrayCombine
array_diffArrayDiff
array_filterArrayFilter
array_flipArrayFlip
array_intersectArrayIntersect
array_keysArrayKeys
array_key_existsArrayKeyExists
array_padArrayPad
array_popArrayPop
array_pushArrayPush
array_reverseArraySlice
array_sliceArrayReverse
array_sumArraySum
array_shiftArrayShift
array_unshiftArrayUnshift
array_uniqueArrayUnique
countCount
in_arrayInArray
key_existsKeyExists
sortSort
rsortRsort

Ctype Functions

PHP functionGolang function
ctype_alnumCtypeAlnum
ctype_alphaCtypeAlpha
ctype_cntrlCtypeCntrl
ctype_digitCtypeDigit
ctype_graphCtypeGraph
ctype_lowerCtypeLower
ctype_printCtypePrint
ctype_punctCtypePunct
ctype_spaceCtypeSpace
ctype_upperCtypeUpper
ctype_xdigitCtypeXdigit

Filesystem Functions

PHP functionGolang function
basenameBasename
dirnameDirname DirnameWithLevels
realpathRealpath
touchTouch
unlinkUnlink
mkdirMkdir
rmdirRmdir
symlinkSymlink
linkLink
chmodChmod
chownChown
is_fileIsFile
is_dirIsDir
is_executableIsExecutable
is_readableIsReadable
is_writableIsWritable
is_linkIsLink
file_existsFileExists
filesizeFilesize
copyCopy
renameRename
file_get_contentsFileGetContents
file_put_contentsFilePutContents

Directory Functions

PHP functionGolang function
getcwdGetcwd
chdirChdir
scandirScandir

Image Functions

PHP functionGolang function
getimagesizeGetImageSize
getimagesizefromstringGetImageSizeFromString

Network Functions

PHP functionGolang function
gethostbyaddrGetHostByAddr
gethostbynameGetHostByName
gethostbynamelGetHostByNamel
gethostnameGetHostName
ip2longIP2Long
long2ipLong2IP

JSON Functions

PHP functionGolang function
json_decodeJSONDecode
json_encodeJSONEncode

CSPRNG Functions

PHP functionGolang function
random_bytesRandomBytes

URL Functions

PHP functionGolang function
base64_decodeBase64Decode
base64_encodeBase64Encode
get_headersGetHeaders
get_meta_tagsGetMetaTags
http_build_queryHTTPBuildQuery
parse_urlParseURL
rawurldecodeRawURLDecode
rawurlencodeRawURLEncode
urldecodeURLDecode
urlencodeURLEncode

Misc Functions

PHP functionGolang function
getenvGetenv
putenvPutenv
memory_get_usageMemoryGetUsage

Install

go get github.com/hyperjiang/php

Usage

import (
    "fmt"
    "github.com/hyperjiang/php"
)

// Date/Time functions

fmt.Println(php.Strtotime("2017-07-14 02:40:00")) // output: 1500000000

fmt.Println(php.Strtotime("2017-07-14T10:40:00+08:00")) // output: 1500000000

fmt.Println(php.Date("Y-m-d H:i:s", 1500000000)) // output: 2017-07-14 02:40:00

fmt.Println(php.Date("c", 1500000000)) // output: 2017-07-14T02:40:00+00:00

// String functions

str := "abcdef"

fmt.Println(php.Substr(str, 1, 0)) // bcdef
fmt.Println(php.Substr(str, 1, 3)) // bcd
fmt.Println(php.Substr(str, 0, 4)) // abcd
fmt.Println(php.Substr(str, -1, 1)) // f
fmt.Println(php.Substr(str, 0, -1)) // abcde

// Math functions

fmt.Println(php.Round(5.055, 2)) // 5.06

// Array functions

arr := []string{"1", "1", "2", "3", "a", "ab", "abc", "abc", "abc", "Abc"}
fmt.Println(php.ArrayUnique(arr)) // [abc Abc 1 2 3 a ab]
fmt.Println(php.InArray("a", arr)) // true

For more usage you can find it out from test files.

# Functions

Abs returns the absolute value of number.
Addslashes quote string with slashes The characters to be escaped are single quote ('), double quote (") and backslash (\).
ArrayChunk splits an array into chunks, returns nil if size < 1.
ArrayColumn returns the values from a single column in the input array.
ArrayCombine creates an array by using one array for keys and another for its values.
ArrayDiff computes the difference of arrays.
ArrayFilter filters elements of an array using a callback function.
ArrayFlip exchanges all keys with their associated values in an array.
ArrayIntersect computes the intersection of arrays.
ArrayKeyExists is alias of KeyExists().
ArrayKeys returns all the keys or a subset of the keys of an array.
ArrayPad pads array to the specified length with a value.
ArrayPop pops the element off the end of array.
ArrayPush pushes one or more elements onto the end of array, returns the new number of elements in the array.
ArrayReverse returns an array with elements in reverse order.
ArrayShift shifts an element off the beginning of array.
ArraySlice extracts a slice of the array.
ArraySum returns the sum of values in an array.
ArrayUnique removes duplicate values from an array, if the input is empty then return the original input.
ArrayUnshift prepends one or more elements to the beginning of a array, returns the new number of elements in the array.
Base64Decode decodes data encoded with MIME base64.
Base64Encode encodes data with MIME base64.
BaseConvert converts a number between arbitrary bases.
Basename returns trailing name component of path.
Bin2hex converts binary data into hexadecimal representation.
Bindec converts a binary number to an integer.
Ceil returns the next highest integer value by rounding up value if necessary.
Chdir changes current directory to dir.
Checkdate validates a Gregorian date.
Chmod changes file mode.
Chown changes file owner and group.
Chr returns a one-character string containing the character specified by ascii.
Copy copies the src file to dst, any existing file will be overwritten and will not copy file attributes.
Count counts all elements in an array or map.
Crc32 calculates the crc32 polynomial of a string.
CtypeAlnum returns TRUE if every character in text is either a letter or a digit, FALSE otherwise.
CtypeAlpha returns TRUE if every character in text is a letter, FALSE otherwise.
CtypeCntrl returns TRUE if every character in text is a control character from the current locale, FALSE otherwise.
CtypeDigit returns TRUE if every character in the string text is a decimal digit, FALSE otherwise.
CtypeGraph returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise.
CtypeLower returns TRUE if every character in text is a lowercase letter.
CtypePrint returns TRUE if every character in text will actually create output (including blanks), returns FALSE if text contains control characters or characters that do not have any output or control function at all.
CtypePunct returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise.
CtypeSpace returns TRUE if every character in text creates some sort of white space, FALSE otherwise Besides the blank character this also includes tab, vertical tab, line feed, carriage return and form feed characters.
CtypeUpper returns TRUE if every character in text is an uppercase letter.
CtypeXdigit returns TRUE if every character in text is a hexadecimal 'digit', that is a decimal digit or a character from [A-Fa-f] , FALSE otherwise.
Date returns a string formatted according to the given format string using the given integer timestamp Note that the timezone is set to UTC.
DateAdd adds an amount of days, months, years, hours, minutes and seconds to the time t.
DateCreate parses a date/time string and return a time.Time.
DateCreateFromFormat parses a date/time string according to a specified format.
DateDateSet sets the date by year, month and day.
DateDefaultTimezoneGet gets the default timezone.
DateDefaultTimezoneSet sets the default timezone.
DateDiff returns the difference between two times (t2 - t1).
DateFormat returns a string formatted according to the given format string using the given time.
DateIntervalCreateFromDateString returns a time.Duration from the given string.
DateISODateSet sets a date according to the ISO 8601 standard - using weeks and day offsets rather than specific dates.
DateModify alter the time by the given format.
DateOffsetGet returns the timezone offset.
DateSub subtracts an amount of days, months, years, hours, minutes and seconds from the time t.
DateTimestampGet gets the Unix timestamp.
DateTimestampSet sets the date and time based on an Unix timestamp.
DateTimezoneGet gets the timezone of the given time.
DateTimezoneSet returns a copy of t with the given timezone.
Decbin converts decimal to binary.
Dechex converts decimal to hexadecimal.
Decoct converts decimal to octal.
DefaultNumberFormat is default NumberFormat for english notation with thousands separator.
Dirname returns a parent directory's path.
DirnameWithLevels returns a parent directory's path which is levels up from the current directory.
Explode returns an slice of strings, each of which is a substring of str formed by splitting it on boundaries formed by the string delimiter.
FileExists checks whether a file or directory exists.
FileGetContents reads entire file into a string.
FilePutContents writes data to a file.
FileSize gets file size.
FirstDateOfLastMonth gets the first date of last month.
FirstDateOfMonth gets the first date of the month which the given time is in.
FirstDateOfNextMonth gets the first date of next month.
Floor returns the next lowest integer value by rounding down value if necessary.
Getcwd gets the current working directory, it will return empty string when error occurs.
Getenv gets the value of an environment variable.
GetHeaders fetches all the headers sent by the server in response to an HTTP request.
GetHostByAddr gets the Internet host name corresponding to a given IP address.
GetHostByName gets the IPv4 address corresponding to a given Internet host name.
GetHostByNamel gets a list of IPv4 addresses corresponding to a given Internet host name.
GetHostName gets the host name.
GetImageSize gets the size of an image.
GetImageSizeFromString gets the size of an image from a string.
GetMetaTags extracts all meta tag content attributes from http content and returns an array.
Hex2bin decodes a hexadecimally encoded binary string.
Hexdec converts hexadecimal to decimal.
HTMLSpecialchars converts special characters to HTML entities.
HTMLSpecialcharsDecode converts special HTML entities back to characters.
HTTPBuildQuery generate URL-encoded query string.
Implode returns a string containing a string representation of all the slice elements in the same order, with the glue string between each element.
InArray checks if a value exists in an array needle is the element to search, haystack is the slice to be searched.
IP2Long converts a string containing an (IPv4) Internet Protocol dotted address into a long integer.
Ireplace is case-insensitive version of Replace().
IsDir tells whether the filename is a directory.
IsExecutable tells whether the filename is executable.
IsFile tells whether the filename is a regular file.
IsLeapYear checks if the given time is in a leap year.
IsLink tells whether the filename is a symbolic link.
IsReadable tells whether a file exists and is readable.
IsWritable tells whether the filename is writable.
JSONDecode decodes a JSON string and stores the result in the value pointed to by v Be aware that this is different with php json_decode.
JSONEncode returns a string containing the JSON representation of the supplied value.
KeyExists checks if the given key or index exists in the array.
LastDateOfMonth gets the last date of the month which the given time is in.
Lcfirst make a string's first character lowercase.
Link create a hard link.
LocalDate returns a string formatted according to the given format string using the given integer timestamp Note that the timezone is using local timezone.
Long2IP converts an long integer address into a string in (IPv4) Internet standard dotted format.
Ltrim strips whitespace (or other characters) from the beginning of a string.
Md5 calculate the md5 hash of a string.
Md5File calculates the md5 hash of a given file.
MemoryGetUsage returns the amount of allocated memory in bytes Set realUsage to TRUE to get total memory allocated from system, including unused pages If realUsage is FALSE then only the used memory is reported.
Microtime returns current Unix timestamp with microseconds.
Mkdir attempts to create the directory specified by pathname.
MtRand is alias of Rand().
NumberFormat formats a number with grouped thousands decimals: sets the number of decimal points decPoint: sets the separator for the decimal point thousandsSep: sets the thousands separator.
Octdec converts octal to decimal.
Ord return ASCII value of character.
ParseDocument parses a document for meta data.
ParseURL parses a URL and return its components.
Pi gets value of pi.
Putenv sets the value of an environment variable The setting should be a key-value pair, like "FOO=BAR".
Rand generates a random integer.
RandomBytes generates cryptographically secure pseudo-random bytes.
RandomString generates cryptographically secure pseudo-random bytes and return its hexadecimal representation.
RawURLDecode decodes URL-encoded string.
RawURLEncode is URL-encode according to RFC 3986.
Realpath returns canonicalized absolute pathname.
Rename renames a file or directory.
Replace all occurrences of the search string with the replacement string This function is an implement of PHP's str_replace see http://php.net/manual/en/function.str-replace.php.
Rmdir removes empty directory.
Round returns the rounded value of val to specified precision (number of digits after the decimal point) Note that we limit the range of precision to [-14, 14] by default.
Rsort sorts an array in reverse order (highest to lowest).
Rtrim strips whitespace (or other characters) from the end of a string.
Scandir lists files and directories inside the specified path.
Sha1 calculates the sha1 hash of a string.
Sha1File calculates the sha1 hash of a file.
SimilarText calculate the similarity between two strings returns the number of matching chars in both strings and the similarity percent note that there is a little difference between the original php function that a multi-byte character is counted as 1 while it would be 2 in php This function is case sensitive.
Sort sorts an array (lowest to highest).
Stripos find position of the first occurrence of a case-insensitive substring in a string.
Stripslashes un-quotes a quoted string.
Stristr is case-insensitive Strstr().
Strlen get string length A multi-byte character is counted as 1.
StrPad pads a string to a certain length with another string.
Strpos find position of first occurrence of string in a string It's multi-byte safe.
StrRepeat repeats a string.
Strrev reverses a string.
Strripos find the position of the last occurrence of a case-insensitive substring in a string.
Strrpos find the position of the last occurrence of a substring in a string.
Strstr find the first occurrence of a string.
Strtolower makes a string lowercase.
Strtotime parses any English textual datetime description into a Unix timestamp, default timezone is UTC if you do not specify one e.g.
Strtoupper makes a string uppercase.
StrWordCount returns an array containing all the words found inside the string.
Substr returns the portion of string specified by the start and length parameters The behaviour of this function is mostly the same as the PHP mb_substr function, see http://php.net/manual/en/function.mb-substr.php except that: 1) If start or length is invalid, empty string will be return 2) If length is 0, the substring starting from start until the end of the string will be returned.
Symlink creates a symbolic link.
Time returns current Unix timestamp.
Today returns a string formatted according to the given format string using current timestamp Note that the timezone is using local timezone.
Touch creates the file if it does not exist.
Trim strips whitespace (or other characters) from the beginning and end of a string.
Ucfirst make a string's first character uppercase.
Ucname uppercases names.
Ucwords uppercases the first character of each word in a string.
Unlink deletes a file.
URLDecode decodes any %## encoding in the given string.
URLEncode returns a string in which all non-alphanumeric characters except -_.

# Constants

PadTypes for StrPad.
PadTypes for StrPad.
PadTypes for StrPad.

# Variables

MaxPrecision is the default max precision for math functions.

# Structs

ImageInfo stores the info of an image.

# Interfaces

Real is a type constraint for real number.

# Type aliases

RuneMatchFunc is function to check if a rune match some condition.