php

package module
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 23, 2022 License: MIT Imports: 37 Imported by: 7

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 function Golang function
checkdate Checkdate
date Date
strtotime Strtotime
time Time
microtime Microtime
date_add DateAdd
date_create_from_format DateCreateFromFormat
date_create DateCreate
date_date_set DateDateSet
date_default_timezone_get DateDefaultTimezoneGet
date_default_timezone_set DateDefaultTimezoneSet
date_diff DateDiff
date_format DateFormat
date_interval_create_from_date_string DateIntervalCreateFromDateString
date_isodate_set DateISODateSet
date_modify DateModify
date_offset_get DateOffsetGet
date_sub DateSub
date_timestamp_get DateTimestampGet
date_timestamp_set DateTimestampSet
date_timezone_get DateTimezoneGet
date_timezone_set DateTimezoneSet
String Functions
PHP function Golang function
addslashes Addslashes
chr Chr
crc32 Crc32
explode Explode
bin2hex Bin2hex
hex2bin Hex2bin
htmlspecialchars HTMLSpecialchars
htmlspecialchars_decode HTMLSpecialcharsDecode
implode Implode
str_ireplace Ireplace
lcfirst Lcfirst
md5 Md5
md5_file Md5File
sha1 Sha1
sha1_file Sha1File
number_format NumberFormat
ord Ord
str_replace Replace
similar_text SimilarText
stripslashes Stripslashes
mb_stripos Stripos
mb_stristr Stristr
mb_strlen Strlen
mb_strpos Strpos
mb_strripos Strripos
mb_strrpos Strrpos
mb_strstr Strstr
mb_substr Substr
str_pad StrPad
str_repeat StrRepeat
strrev Strrev
strtolower Strtolower
strtoupper Strtoupper
str_word_count StrWordCount
ltrim Ltrim
rtrim Rtrim
trim Trim
ucfirst Ucfirst
ucwords Ucwords
Math Functions
PHP function Golang function
abs Abs
base_convert BaseConvert
bindec Bindec
decbin Decbin
dechex Dechex
hexdec Hexdec
decoct Decoct
octdec Octdec
ceil Ceil
floor Floor
pi Pi
mt_rand MtRand
rand Rand
round Round
Array Functions
PHP function Golang function
array_chunk ArrayChunk
array_column ArrayColumn
array_combine ArrayCombine
array_diff ArrayDiff
array_filter ArrayFilter
array_flip ArrayFlip
array_intersect ArrayIntersect
array_keys ArrayKeys
array_key_exists ArrayKeyExists
array_pad ArrayPad
array_pop ArrayPop
array_push ArrayPush
array_reverse ArraySlice
array_slice ArrayReverse
array_sum ArraySum
array_shift ArrayShift
array_unshift ArrayUnshift
array_unique ArrayUnique
count Count
in_array InArray
key_exists KeyExists
sort Sort
rsort Rsort
Ctype Functions
PHP function Golang function
ctype_alnum CtypeAlnum
ctype_alpha CtypeAlpha
ctype_cntrl CtypeCntrl
ctype_digit CtypeDigit
ctype_graph CtypeGraph
ctype_lower CtypeLower
ctype_print CtypePrint
ctype_punct CtypePunct
ctype_space CtypeSpace
ctype_upper CtypeUpper
ctype_xdigit CtypeXdigit
Filesystem Functions
PHP function Golang function
basename Basename
dirname Dirname DirnameWithLevels
realpath Realpath
touch Touch
unlink Unlink
mkdir Mkdir
rmdir Rmdir
symlink Symlink
link Link
chmod Chmod
chown Chown
is_file IsFile
is_dir IsDir
is_executable IsExecutable
is_readable IsReadable
is_writable IsWritable
is_link IsLink
file_exists FileExists
filesize Filesize
copy Copy
rename Rename
file_get_contents FileGetContents
file_put_contents FilePutContents
Directory Functions
PHP function Golang function
getcwd Getcwd
chdir Chdir
scandir Scandir
Image Functions
PHP function Golang function
getimagesize GetImageSize
getimagesizefromstring GetImageSizeFromString
Network Functions
PHP function Golang function
gethostbyaddr GetHostByAddr
gethostbyname GetHostByName
gethostbynamel GetHostByNamel
gethostname GetHostName
ip2long IP2Long
long2ip Long2IP
JSON Functions
PHP function Golang function
json_decode JSONDecode
json_encode JSONEncode
CSPRNG Functions
PHP function Golang function
random_bytes RandomBytes
URL Functions
PHP function Golang function
base64_decode Base64Decode
base64_encode Base64Encode
get_headers GetHeaders
get_meta_tags GetMetaTags
http_build_query HTTPBuildQuery
parse_url ParseURL
rawurldecode RawURLDecode
rawurlencode RawURLEncode
urldecode URLDecode
urlencode URLEncode
Misc Functions
PHP function Golang function
getenv Getenv
putenv Putenv
memory_get_usage MemoryGetUsage

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.

Documentation

Overview

Package php implements some PHP functions

See README.md for more info.

Index

Constants

View Source
const (
	StrPadRight = iota
	StrPadLeft
	StrPadBoth
)

PadTypes for StrPad

Variables

View Source
var MaxPrecision = 14

MaxPrecision is the default max precision for math functions

Functions

func Abs

func Abs[T Real](number T) T

Abs returns the absolute value of number

func Addslashes

func Addslashes(str string) string

Addslashes quote string with slashes

The characters to be escaped are single quote ('), double quote (") and backslash (\)

func ArrayChunk

func ArrayChunk[T comparable](array []T, size int) [][]T

ArrayChunk splits an array into chunks, returns nil if size < 1

func ArrayColumn

func ArrayColumn[T comparable](input []map[string]T, columnKey string) []T

ArrayColumn returns the values from a single column in the input array

func ArrayCombine

func ArrayCombine[K, V comparable](keys []K, values []V) map[K]V

ArrayCombine creates an array by using one array for keys and another for its values

func ArrayDiff

func ArrayDiff[T comparable](array1, array2 []T) []T

ArrayDiff computes the difference of arrays

func ArrayFilter

func ArrayFilter(input any, callback func(any) bool) any

ArrayFilter filters elements of an array using a callback function

func ArrayFlip

func ArrayFlip(input any) any

ArrayFlip exchanges all keys with their associated values in an array

func ArrayIntersect

func ArrayIntersect[T comparable](array1, array2 []T) []T

ArrayIntersect computes the intersection of arrays

func ArrayKeyExists

func ArrayKeyExists[K, V comparable](k K, m map[K]V) bool

ArrayKeyExists is alias of KeyExists()

func ArrayKeys

func ArrayKeys(input any) any

ArrayKeys returns all the keys or a subset of the keys of an array

func ArrayPad

func ArrayPad[T comparable](array []T, size int, value T) []T

ArrayPad pads array to the specified length with a value

func ArrayPop

func ArrayPop[T comparable](s *[]T) T

ArrayPop pops the element off the end of array

func ArrayPush

func ArrayPush[T comparable](s *[]T, elements ...T) int

ArrayPush pushes one or more elements onto the end of array, returns the new number of elements in the array

func ArrayReverse

func ArrayReverse[T comparable](s []T) []T

ArrayReverse returns an array with elements in reverse order

func ArrayShift

func ArrayShift[T comparable](s *[]T) T

ArrayShift shifts an element off the beginning of array

func ArraySlice

func ArraySlice[T comparable](array []T, offset, length uint) []T

ArraySlice extracts a slice of the array

func ArraySum

func ArraySum[T constraints.Ordered](array []T) T

ArraySum returns the sum of values in an array

func ArrayUnique

func ArrayUnique[T comparable](arr []T) []T

ArrayUnique removes duplicate values from an array, if the input is empty then return the original input

func ArrayUnshift

func ArrayUnshift[T comparable](s *[]T, elements ...T) int

ArrayUnshift prepends one or more elements to the beginning of a array, returns the new number of elements in the array.

func Base64Decode added in v0.5.0

func Base64Decode(data string) (string, error)

Base64Decode decodes data encoded with MIME base64. Returns error if data is in invalid format.

func Base64Encode added in v0.5.0

func Base64Encode(data string) string

Base64Encode encodes data with MIME base64

func BaseConvert

func BaseConvert(number string, frombase, tobase int) (string, error)

BaseConvert converts a number between arbitrary bases

func Basename

func Basename(path string) string

Basename returns trailing name component of path

func Bin2hex

func Bin2hex(src []byte) string

Bin2hex converts binary data into hexadecimal representation

func Bindec

func Bindec(str string) (string, error)

Bindec converts a binary number to an integer

func Ceil

func Ceil(value float64) float64

Ceil returns the next highest integer value by rounding up value if necessary

func Chdir added in v0.4.0

func Chdir(dir string) error

Chdir changes current directory to dir

func Checkdate

func Checkdate(month, day, year int) bool

Checkdate validates a Gregorian date

func Chmod

func Chmod(filename string, mode os.FileMode) error

Chmod changes file mode

func Chown

func Chown(filename string, uid, gid int) error

Chown changes file owner and group

func Chr

func Chr(ascii int) string

Chr returns a one-character string containing the character specified by ascii

func Copy

func Copy(src, dst string) error

Copy copies the src file to dst, any existing file will be overwritten and will not copy file attributes

func Count

func Count(v any) int

Count counts all elements in an array or map

func Crc32

func Crc32(str string) uint32

Crc32 calculates the crc32 polynomial of a string

func CtypeAlnum

func CtypeAlnum(text string) bool

CtypeAlnum returns TRUE if every character in text is either a letter or a digit, FALSE otherwise

func CtypeAlpha

func CtypeAlpha(text string) bool

CtypeAlpha returns TRUE if every character in text is a letter, FALSE otherwise

func CtypeCntrl

func CtypeCntrl(text string) bool

CtypeCntrl returns TRUE if every character in text is a control character from the current locale, FALSE otherwise

func CtypeDigit

func CtypeDigit(text string) bool

CtypeDigit returns TRUE if every character in the string text is a decimal digit, FALSE otherwise

func CtypeGraph

func CtypeGraph(text string) bool

CtypeGraph returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise

func CtypeLower

func CtypeLower(text string) bool

CtypeLower returns TRUE if every character in text is a lowercase letter

func CtypePrint

func CtypePrint(text string) bool

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

func CtypePunct

func CtypePunct(text string) bool

CtypePunct returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise

func CtypeSpace

func CtypeSpace(text string) bool

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

func CtypeUpper

func CtypeUpper(text string) bool

CtypeUpper returns TRUE if every character in text is an uppercase letter

func CtypeXdigit

func CtypeXdigit(text string) bool

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

func Date

func Date(f string, timestamp int64) string

Date returns a string formatted according to the given format string using the given integer timestamp

Note that the timezone is set to UTC

func DateAdd added in v0.3.0

func DateAdd(t time.Time, d time.Duration) time.Time

DateAdd adds an amount of days, months, years, hours, minutes and seconds to the time t

func DateCreate added in v0.3.0

func DateCreate(str string) (time.Time, error)

DateCreate parses a date/time string and return a time.Time. Supported Date and Time Formats: https://www.php.net/manual/en/datetime.formats.php

func DateCreateFromFormat added in v0.3.0

func DateCreateFromFormat(f string, t string) (time.Time, error)

DateCreateFromFormat parses a date/time string according to a specified format

func DateDateSet added in v0.3.0

func DateDateSet(year, month, day int) (time.Time, error)

DateDateSet sets the date by year, month and day

func DateDefaultTimezoneGet added in v0.3.0

func DateDefaultTimezoneGet() string

DateDefaultTimezoneGet gets the default timezone

func DateDefaultTimezoneSet added in v0.3.0

func DateDefaultTimezoneSet(tz string) error

DateDefaultTimezoneSet sets the default timezone

func DateDiff added in v0.3.0

func DateDiff(t1 time.Time, t2 time.Time) time.Duration

DateDiff returns the difference between two times (t2 - t1)

func DateFormat added in v0.3.0

func DateFormat(t time.Time, f string) string

DateFormat returns a string formatted according to the given format string using the given time

func DateISODateSet added in v0.3.0

func DateISODateSet(year, week, day int) (time.Time, error)

DateISODateSet sets a date according to the ISO 8601 standard - using weeks and day offsets rather than specific dates

func DateIntervalCreateFromDateString added in v0.3.0

func DateIntervalCreateFromDateString(str string) (time.Duration, error)

DateIntervalCreateFromDateString returns a time.Duration from the given string

func DateModify added in v0.3.0

func DateModify(t time.Time, modify string) (time.Time, error)

DateModify alter the time by the given format

func DateOffsetGet added in v0.3.0

func DateOffsetGet(t time.Time) int

DateOffsetGet returns the timezone offset

func DateSub added in v0.3.0

func DateSub(t time.Time, d time.Duration) time.Time

DateSub subtracts an amount of days, months, years, hours, minutes and seconds from the time t

func DateTimestampGet added in v0.3.0

func DateTimestampGet(t time.Time) int64

DateTimestampGet gets the Unix timestamp

func DateTimestampSet added in v0.3.0

func DateTimestampSet(timestamp int64) time.Time

DateTimestampSet sets the date and time based on an Unix timestamp

func DateTimezoneGet added in v0.3.0

func DateTimezoneGet(t time.Time) string

DateTimezoneGet gets the timezone of the given time

func DateTimezoneSet added in v0.3.0

func DateTimezoneSet(t time.Time, tz string) (time.Time, error)

DateTimezoneSet returns a copy of t with the given timezone

func Decbin

func Decbin(number int64) string

Decbin converts decimal to binary

func Dechex

func Dechex(number int64) string

Dechex converts decimal to hexadecimal

func Decoct

func Decoct(number int64) string

Decoct converts decimal to octal

func DefaultNumberFormat

func DefaultNumberFormat(number float64, decimals int) string

DefaultNumberFormat is default NumberFormat for english notation with thousands separator

func Dirname

func Dirname(path string) string

Dirname returns a parent directory's path

func DirnameWithLevels

func DirnameWithLevels(path string, levels int) string

DirnameWithLevels returns a parent directory's path which is levels up from the current directory.

func Explode

func Explode(delimiter, str string) []string

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

func FileExists

func FileExists(filename string) bool

FileExists checks whether a file or directory exists

func FileGetContents

func FileGetContents(filename string) (string, error)

FileGetContents reads entire file into a string

func FilePutContents

func FilePutContents(filename string, data string) error

FilePutContents writes data to a file

func FileSize

func FileSize(filename string) (int64, error)

FileSize gets file size

func FirstDateOfLastMonth

func FirstDateOfLastMonth(t time.Time) time.Time

FirstDateOfLastMonth gets the first date of last month

func FirstDateOfMonth

func FirstDateOfMonth(t time.Time) time.Time

FirstDateOfMonth gets the first date of the month which the given time is in

func FirstDateOfNextMonth

func FirstDateOfNextMonth(t time.Time) time.Time

FirstDateOfNextMonth gets the first date of next month

func Floor

func Floor(value float64) float64

Floor returns the next lowest integer value by rounding down value if necessary

func GetHeaders added in v0.5.0

func GetHeaders(url string) (http.Header, error)

GetHeaders fetches all the headers sent by the server in response to an HTTP request

func GetHostByAddr

func GetHostByAddr(ipAddress string) (string, error)

GetHostByAddr gets the Internet host name corresponding to a given IP address

func GetHostByName

func GetHostByName(hostname string) (string, error)

GetHostByName gets the IPv4 address corresponding to a given Internet host name

func GetHostByNamel

func GetHostByNamel(hostname string) ([]string, error)

GetHostByNamel gets a list of IPv4 addresses corresponding to a given Internet host name

func GetHostName

func GetHostName() (string, error)

GetHostName gets the host name

func GetMetaTags added in v0.5.0

func GetMetaTags(url string) (map[string]string, error)

GetMetaTags extracts all meta tag content attributes from http content and returns an array

func Getcwd added in v0.4.0

func Getcwd() string

Getcwd gets the current working directory, it will return empty string when error occurs

func Getenv

func Getenv(varname string) string

Getenv gets the value of an environment variable

func HTMLSpecialchars

func HTMLSpecialchars(str string) string

HTMLSpecialchars converts special characters to HTML entities

func HTMLSpecialcharsDecode

func HTMLSpecialcharsDecode(str string) string

HTMLSpecialcharsDecode converts special HTML entities back to characters

func HTTPBuildQuery added in v0.5.0

func HTTPBuildQuery(data map[string]any) string

HTTPBuildQuery generate URL-encoded query string

func Hex2bin

func Hex2bin(str string) []byte

Hex2bin decodes a hexadecimally encoded binary string

func Hexdec

func Hexdec(str string) (int64, error)

Hexdec converts hexadecimal to decimal

func IP2Long

func IP2Long(ipAddress string) uint32

IP2Long converts a string containing an (IPv4) Internet Protocol dotted address into a long integer

func Implode

func Implode(glue string, pieces []string) 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

func InArray

func InArray[T comparable](needle T, haystack []T) bool

InArray checks if a value exists in an array

needle is the element to search, haystack is the slice to be searched

func Ireplace

func Ireplace(search, replace any, subject string) string

Ireplace is case-insensitive version of Replace()

func IsDir

func IsDir(filename string) bool

IsDir tells whether the filename is a directory

func IsExecutable

func IsExecutable(filename string) bool

IsExecutable tells whether the filename is executable

func IsFile

func IsFile(filename string) bool

IsFile tells whether the filename is a regular file

func IsLeapYear

func IsLeapYear(t time.Time) bool

IsLeapYear checks if the given time is in a leap year

func IsLink(filename string) bool

IsLink tells whether the filename is a symbolic link

func IsReadable

func IsReadable(filename string) bool

IsReadable tells whether a file exists and is readable

func IsWritable

func IsWritable(filename string) bool

IsWritable tells whether the filename is writable

func JSONDecode added in v0.2.1

func JSONDecode(jsonStr string, v any) error

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

func JSONEncode added in v0.2.1

func JSONEncode(value any) (string, error)

JSONEncode returns a string containing the JSON representation of the supplied value

func KeyExists

func KeyExists[K, V comparable](k K, m map[K]V) bool

KeyExists checks if the given key or index exists in the array

func LastDateOfMonth

func LastDateOfMonth(t time.Time) time.Time

LastDateOfMonth gets the last date of the month which the given time is in

func Lcfirst

func Lcfirst(str string) string

Lcfirst make a string's first character lowercase

func Link(target, link string) error

Link create a hard link

func LocalDate

func LocalDate(f string, timestamp int64) string

LocalDate returns a string formatted according to the given format string using the given integer timestamp

Note that the timezone is using local timezone

func Long2IP

func Long2IP(properAddress uint32) string

Long2IP converts an long integer address into a string in (IPv4) Internet standard dotted format

func Ltrim

func Ltrim(str string, chars ...string) string

Ltrim strips whitespace (or other characters) from the beginning of a string

func Md5

func Md5(str string) string

Md5 calculate the md5 hash of a string

func Md5File

func Md5File(filename string) (string, error)

Md5File calculates the md5 hash of a given file

func MemoryGetUsage

func MemoryGetUsage(realUsage bool) uint64

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

func Microtime

func Microtime() float64

Microtime returns current Unix timestamp with microseconds

func Mkdir

func Mkdir(pathname string, mode os.FileMode, recursive bool) error

Mkdir attempts to create the directory specified by pathname

func MtRand

func MtRand(min, max int) int

MtRand is alias of Rand()

func NumberFormat

func NumberFormat(number float64, decimals int, decPoint, thousandsSep string) string

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

func Octdec

func Octdec(str string) (int64, error)

Octdec converts octal to decimal

func Ord

func Ord(character string) rune

Ord return ASCII value of character

func ParseDocument added in v0.5.0

func ParseDocument(doc io.Reader) map[string]string

ParseDocument parses a document for meta data

func ParseURL added in v0.5.0

func ParseURL(str string) (*url.URL, error)

ParseURL parses a URL and return its components

func Pi

func Pi() float64

Pi gets value of pi

func Putenv

func Putenv(setting string) error

Putenv sets the value of an environment variable

The setting should be a key-value pair, like "FOO=BAR"

func Rand

func Rand(min, max int) int

Rand generates a random integer

func RandomBytes

func RandomBytes(length int) []byte

RandomBytes generates cryptographically secure pseudo-random bytes

func RandomString

func RandomString(length int) string

RandomString generates cryptographically secure pseudo-random bytes and return its hexadecimal representation

func RawURLDecode added in v0.5.0

func RawURLDecode(str string) string

RawURLDecode decodes URL-encoded string.

RawURLDecode is identical to URLDecode except that it does not unescape '+' to ' ' (space).

func RawURLEncode added in v0.5.0

func RawURLEncode(str string) string

RawURLEncode is URL-encode according to RFC 3986.

RawURLEncode is identical to URLEncode except that it does not escape space to +.

func Realpath

func Realpath(path string) string

Realpath returns canonicalized absolute pathname

func Rename

func Rename(oldname, newname string) error

Rename renames a file or directory

func Replace

func Replace(search, replace any, subject string) string

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

func Rmdir

func Rmdir(dirname string) error

Rmdir removes empty directory

func Round

func Round(val float64, precision int) float64

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

func Rsort

func Rsort[T constraints.Ordered](array []T) []T

Rsort sorts an array in reverse order (highest to lowest)

func Rtrim

func Rtrim(str string, chars ...string) string

Rtrim strips whitespace (or other characters) from the end of a string

func Scandir added in v0.4.0

func Scandir(dir string) ([]string, error)

Scandir lists files and directories inside the specified path

func Sha1

func Sha1(str string) string

Sha1 calculates the sha1 hash of a string

func Sha1File

func Sha1File(path string) (string, error)

Sha1File calculates the sha1 hash of a file

func SimilarText

func SimilarText(first, second string) (count int, percent float32)

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

func Sort

func Sort[T constraints.Ordered](array []T) []T

Sort sorts an array (lowest to highest)

func StrPad

func StrPad(input string, padLength int, padString string, padType int) string

StrPad pads a string to a certain length with another string

func StrRepeat

func StrRepeat(input string, multiplier int) string

StrRepeat repeats a string

func StrWordCount

func StrWordCount(str string) []string

StrWordCount returns an array containing all the words found inside the string

func Stripos

func Stripos(haystack, needle string) int

Stripos find position of the first occurrence of a case-insensitive substring in a string

func Stripslashes

func Stripslashes(str string) string

Stripslashes un-quotes a quoted string

func Stristr

func Stristr(haystack, needle string) string

Stristr is case-insensitive Strstr()

func Strlen

func Strlen(str string) int

Strlen get string length

A multi-byte character is counted as 1

func Strpos

func Strpos(haystack, needle string) int

Strpos find position of first occurrence of string in a string

It's multi-byte safe. return -1 if can not find the substring

func Strrev

func Strrev(str string) string

Strrev reverses a string

func Strripos

func Strripos(haystack, needle string) int

Strripos find the position of the last occurrence of a case-insensitive substring in a string

func Strrpos

func Strrpos(haystack, needle string) int

Strrpos find the position of the last occurrence of a substring in a string

func Strstr

func Strstr(haystack, needle string) string

Strstr find the first occurrence of a string

func Strtolower

func Strtolower(str string) string

Strtolower makes a string lowercase

func Strtotime

func Strtotime(str string) int64

Strtotime parses any English textual datetime description into a Unix timestamp, default timezone is UTC if you do not specify one

e.g. You can specify the timezone to UTC+8 by using yyyy-MM-ddThh:mm:ss+08:00

Returns a timestamp on success, -1 on failure.

Note that this function does not fully cover PHP's strtotime function yet

func Strtoupper

func Strtoupper(str string) string

Strtoupper makes a string uppercase

func Substr

func Substr(str string, start, length int) 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

func Symlink(target, link string) error

Symlink creates a symbolic link

func Time

func Time() int64

Time returns current Unix timestamp

func Today

func Today(f string) string

Today returns a string formatted according to the given format string using current timestamp

Note that the timezone is using local timezone

func Touch

func Touch(filename string) error

Touch creates the file if it does not exist

func Trim

func Trim(str string, chars ...string) string

Trim strips whitespace (or other characters) from the beginning and end of a string

func URLDecode added in v0.5.0

func URLDecode(str string) string

URLDecode decodes any %## encoding in the given string. Plus symbols ('+') are decoded to a space character.

func URLEncode added in v0.5.0

func URLEncode(str string) string

URLEncode returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type.

func Ucfirst

func Ucfirst(str string) string

Ucfirst make a string's first character uppercase

func Ucname

func Ucname(str string) string

Ucname uppercases names

func Ucwords

func Ucwords(str string, fs ...RuneMatchFunc) string

Ucwords uppercases the first character of each word in a string

func Unlink(filename string) error

Unlink deletes a file

Types

type ImageInfo added in v0.2.0

type ImageInfo struct {
	Width  int
	Height int
	Format string
	Mime   string
}

ImageInfo stores the info of an image

func GetImageSize added in v0.2.0

func GetImageSize(filename string) (ImageInfo, error)

GetImageSize gets the size of an image

func GetImageSizeFromString added in v0.2.0

func GetImageSizeFromString(data []byte) (ImageInfo, error)

GetImageSizeFromString gets the size of an image from a string

type Real added in v0.6.3

type Real interface {
	constraints.Integer | constraints.Float
}

Real is a type constraint for real number

type RuneMatchFunc

type RuneMatchFunc func(rune) bool

RuneMatchFunc is function to check if a rune match some condition

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL