PHP String Functions (All on One Page)

Author — Nitish Kumar

addcslashes() — Quote string with slashes in a C style

addslashes() — Quote string with slashes

bin2hex() — Convert binary data into hexadecimal representation

chop() — Alias of rtrim

chr() — Generate a single-byte string from a number

chunk_split() — Split a string into smaller chunks

convert_cyr_string() — Convert from one Cyrillic character set to another

convert_uudecode() — Decode a uuencoded string

convert_uuencode() — Uuencode a string

count_chars() — Return information about characters used in a string

crc32() — Calculates the crc32 polynomial of a string

crypt() — One-way string hashing

echo() — Output one or more strings

explode() — Split a string by a string

fprintf() — Write a formatted string to a stream

get_html_translation_table() — Returns the translation table used by htmlspecialchars and htmlentities

hebrev() — Convert logical Hebrew text to visual text

hebrevc() — Convert logical Hebrew text to visual text with newline conversion

hex2bin() — Decodes a hexadecimally encoded binary string

html_entity_decode() — Convert HTML entities to their corresponding characters

htmlentities() — Convert all applicable characters to HTML entities

htmlspecialchars_decode() — Convert special HTML entities back to characters

htmlspecialchars() — Convert special characters to HTML entities

implode() — Join array elements with a string

join() — Alias of implode

lcfirst() — Make a string’s first character lowercase

levenshtein() — Calculate Levenshtein distance between two strings

localeconv() — Get numeric formatting information

ltrim() — Strip whitespace (or other characters) from the beginning of a string

md5_file() — Calculates the md5 hash of a given file

md5() — Calculate the md5 hash of a string

metaphone() — Calculate the metaphone key of a string

money_format() — Formats a number as a currency string

nl_langinfo() — Query language and locale information

nl2br() — Inserts HTML line breaks before all newlines in a string

number_format() — Format a number with grouped thousands

ord() — Convert the first byte of a string to a value between 0 and 255

parse_str() — Parses the string into variables

print() — Output a string

printf() — Output a formatted string

quoted_printable_decode() — Convert a quoted-printable string to an 8 bit string

quoted_printable_encode() — Convert a 8 bit string to a quoted-printable string

quotemeta() — Quote meta characters

rtrim() — Strip whitespace (or other characters) from the end of a string

setlocale() — Set locale information

sha1_file() — Calculate the sha1 hash of a file

sha1() — Calculate the sha1 hash of a string

similar_text() — Calculate the similarity between two strings

soundex() — Calculate the soundex key of a string

sprintf() — Return a formatted string

sscanf() — Parses input from a string according to a format

str_getcsv() — Parse a CSV string into an array

str_ireplace() — Case-insensitive version of str_replace

str_pad() — Pad a string to a certain length with another string

str_repeat() — Repeat a string

str_replace() — Replace all occurrences of the search string with the replacement string

str_rot13() — Perform the rot13 transform on a string

str_shuffle() — Randomly shuffles a string

str_split() — Convert a string to an array

str_word_count() — Return information about words used in a string

strcasecmp() — Binary safe case-insensitive string comparison

strchr() — Alias of strstr

strcmp() — Binary safe string comparison

strcoll() — Locale based string comparison

strcspn() — Find length of initial segment not matching mask

strip_tags() — Strip HTML and PHP tags from a string

stripcslashes() — Un-quote string quoted with addcslashes

stripos() — Find the position of the first occurrence of a case-insensitive substring in a string

stripslashes() — Un-quotes a quoted string

stristr() — Case-insensitive strstr

strlen() — Get string length

strnatcasecmp() — Case insensitive string comparisons using a “natural order” algorithm

strnatcmp() — String comparisons using a “natural order” algorithm

strncasecmp() — Binary safe case-insensitive string comparison of the first n characters

strncmp() — Binary safe string comparison of the first n characters

strpbrk() — Search a string for any of a set of characters

strpos() — Find the position of the first occurrence of a substring in a string

strrchr() — Find the last occurrence of a character in a string

strrev() — Reverse 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

strspn() — Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask

strstr() — Find the first occurrence of a string

strtok() — Tokenize string

strtolower() — Make a string lowercase

strtoupper() — Make a string uppercase

strtr() — Translate characters or replace substrings

substr_compare() — Binary safe comparison of two strings from an offset, up to length characters

substr_count() — Count the number of substring occurrences

substr_replace() — Replace text within a portion of a string

substr() — Return part of a string

trim() — Strip whitespace (or other characters) from the beginning and end of a string

ucfirst() — Make a string’s first character uppercase

ucwords() — Uppercase the first character of each word in a string

vfprintf() — Write a formatted string to a stream

vprintf() — Output a formatted string

vsprintf() — Return a formatted string

wordwrap() — Wraps a string to a given number of characters

On This Page
  1. PHP addcslashes() Function
    1. What does addcslashes() do?
    2. PHP addcslashes() Syntax
    3. PHP addcslashes() Parameters
    4. PHP addcslashes() Return Value
    5. PHP addcslashes() Working Examples
      1. 1. addcslashes() example
    6. Changelog for PHP addcslashes() Function
  2. PHP addslashes() Function
    1. What does addslashes() do?
    2. PHP addslashes() Syntax
    3. PHP addslashes() Parameters
    4. PHP addslashes() Return Value
    5. PHP addslashes() Working Examples
      1. 1. An addslashes() example
    6. Additional Tips from Fellow Developers
  3. PHP bin2hex() Function
    1. What does bin2hex() do?
    2. PHP bin2hex() Syntax
    3. PHP bin2hex() Parameters
    4. PHP bin2hex() Return Value
    5. Additional Tips from Fellow Developers
  4. PHP chop() Function
    1. What does chop() do?
    2. PHP chop() Syntax
    3. PHP chop() Parameters
    4. Important Points about PHP chop() Function
    5. Additional Tips from Fellow Developers
  5. PHP chr() Function
    1. What does chr() do?
    2. PHP chr() Syntax
    3. PHP chr() Parameters
    4. PHP chr() Return Value
    5. PHP chr() Working Examples
      1. 1. chr() example
      2. 2. Overflow behavior
      3. 3. Building a UTF-8 string from individual bytes
    6. Additional Tips from Fellow Developers
  6. PHP chunk_split() Function
    1. What does chunk_split() do?
    2. PHP chunk_split() Syntax
    3. PHP chunk_split() Parameters
    4. PHP chunk_split() Return Value
    5. PHP chunk_split() Working Examples
      1. 1. chunk_split() example
    6. Additional Tips from Fellow Developers
  7. PHP convert_cyr_string() Function
    1. What does convert_cyr_string() do?
    2. PHP convert_cyr_string() Syntax
    3. PHP convert_cyr_string() Parameters
    4. PHP convert_cyr_string() Return Value
  8. PHP convert_uudecode() Function
    1. What does convert_uudecode() do?
    2. PHP convert_uudecode() Syntax
    3. PHP convert_uudecode() Parameters
    4. PHP convert_uudecode() Return Value
    5. PHP convert_uudecode() Working Examples
      1. 1. convert_uudecode() example
  9. PHP convert_uuencode() Function
    1. What does convert_uuencode() do?
    2. PHP convert_uuencode() Syntax
    3. PHP convert_uuencode() Parameters
    4. PHP convert_uuencode() Return Value
    5. PHP convert_uuencode() Working Examples
      1. 1. convert_uuencode() example
    6. Additional Tips from Fellow Developers
  10. PHP count_chars() Function
    1. What does count_chars() do?
    2. PHP count_chars() Syntax
    3. PHP count_chars() Parameters
    4. PHP count_chars() Return Value
    5. PHP count_chars() Working Examples
      1. 1. count_chars() example
    6. Additional Tips from Fellow Developers
  11. PHP crc32() Function
    1. What does crc32() do?
    2. PHP crc32() Syntax
    3. PHP crc32() Parameters
    4. PHP crc32() Return Value
    5. PHP crc32() Working Examples
      1. 1. Displaying a crc32 checksum
    6. Important Points about PHP crc32() Function
  12. PHP crypt() Function
    1. What does crypt() do?
    2. PHP crypt() Syntax
    3. PHP crypt() Parameters
    4. PHP crypt() Return Value
    5. PHP crypt() Working Examples
      1. 1. crypt() examples
      2. 2. Using crypt() with htpasswd
      3. 3. Using crypt() with different hash types
    6. Changelog for PHP crypt() Function
    7. Important Points about PHP crypt() Function
    8. Additional Tips from Fellow Developers
  13. PHP echo() Function
    1. What does echo() do?
    2. PHP echo() Syntax
    3. PHP echo() Parameters
    4. PHP echo() Return Value
    5. PHP echo() Working Examples
      1. 1. echo examples
  14. PHP explode() Function
    1. What does explode() do?
    2. PHP explode() Syntax
    3. PHP explode() Parameters
    4. PHP explode() Return Value
    5. PHP explode() Working Examples
      1. 1. explode() examples
      2. 2. explode() return examples
      3. 3. limit parameter examples
    6. Changelog for PHP explode() Function
    7. Important Points about PHP explode() Function
    8. Additional Tips from Fellow Developers
  15. PHP fprintf() Function
    1. What does fprintf() do?
    2. PHP fprintf() Syntax
    3. PHP fprintf() Parameters
    4. PHP fprintf() Return Value
    5. PHP fprintf() Working Examples
      1. 1. fprintf(): zero-padded integers
      2. 2. fprintf(): formatting currency
    6. Important Points about PHP fprintf() Function
  16. PHP get_html_translation_table() Function
    1. What does get_html_translation_table() do?
    2. PHP get_html_translation_table() Syntax
    3. PHP get_html_translation_table() Parameters
    4. PHP get_html_translation_table() Return Value
    5. PHP get_html_translation_table() Working Examples
      1. 1. Translation Table Example
    6. Changelog for PHP get_html_translation_table() Function
    7. Important Points about PHP get_html_translation_table() Function
    8. Additional Tips from Fellow Developers
  17. PHP hebrev() Function
    1. What does hebrev() do?
    2. PHP hebrev() Syntax
    3. PHP hebrev() Parameters
    4. PHP hebrev() Return Value
  18. PHP hebrevc() Function
    1. What does hebrevc() do?
    2. PHP hebrevc() Syntax
    3. PHP hebrevc() Parameters
    4. PHP hebrevc() Return Value
  19. PHP hex2bin() Function
    1. What does hex2bin() do?
    2. PHP hex2bin() Syntax
    3. PHP hex2bin() Parameters
    4. PHP hex2bin() Return Value
    5. PHP hex2bin() Working Examples
      1. 1. hex2bin() example
    6. Changelog for PHP hex2bin() Function
    7. Important Points about PHP hex2bin() Function
    8. Additional Tips from Fellow Developers
  20. PHP html_entity_decode() Function
    1. What does html_entity_decode() do?
    2. PHP html_entity_decode() Syntax
    3. PHP html_entity_decode() Parameters
    4. PHP html_entity_decode() Return Value
    5. PHP html_entity_decode() Working Examples
      1. 1. Decoding HTML entities
    6. Changelog for PHP html_entity_decode() Function
    7. Important Points about PHP html_entity_decode() Function
    8. Additional Tips from Fellow Developers
  21. PHP htmlentities() Function
    1. What does htmlentities() do?
    2. PHP htmlentities() Syntax
    3. PHP htmlentities() Parameters
    4. PHP htmlentities() Return Value
    5. PHP htmlentities() Working Examples
      1. 1. A htmlentities() example
      2. 2. Usage of ENT_IGNORE
    6. Changelog for PHP htmlentities() Function
    7. Additional Tips from Fellow Developers
  22. PHP htmlspecialchars() Function
    1. What does htmlspecialchars() do?
    2. PHP htmlspecialchars() Syntax
    3. PHP htmlspecialchars() Parameters
    4. PHP htmlspecialchars() Return Value
    5. PHP htmlspecialchars() Working Examples
      1. 1. htmlspecialchars() example
    6. Changelog for PHP htmlspecialchars() Function
    7. Important Points about PHP htmlspecialchars() Function
    8. Additional Tips from Fellow Developers
  23. PHP htmlspecialchars_decode() Function
    1. What does htmlspecialchars_decode() do?
    2. PHP htmlspecialchars_decode() Syntax
    3. PHP htmlspecialchars_decode() Parameters
    4. PHP htmlspecialchars_decode() Return Value
    5. PHP htmlspecialchars_decode() Working Examples
      1. 1. A htmlspecialchars_decode() example
    6. Changelog for PHP htmlspecialchars_decode() Function
  24. PHP implode() Function
    1. What does implode() do?
    2. PHP implode() Syntax
    3. PHP implode() Parameters
    4. PHP implode() Return Value
    5. PHP implode() Working Examples
      1. 1. implode() example
    6. Important Points about PHP implode() Function
    7. Additional Tips from Fellow Developers
  25. PHP join() Function
    1. What does join() do?
    2. PHP join() Syntax
    3. PHP join() Parameters
  26. PHP lcfirst() Function
    1. What does lcfirst() do?
    2. PHP lcfirst() Syntax
    3. PHP lcfirst() Parameters
    4. PHP lcfirst() Return Value
    5. PHP lcfirst() Working Examples
      1. 1. lcfirst() example
    6. Additional Tips from Fellow Developers
  27. PHP levenshtein() Function
    1. What does levenshtein() do?
    2. PHP levenshtein() Syntax
    3. PHP levenshtein() Parameters
    4. PHP levenshtein() Return Value
    5. PHP levenshtein() Working Examples
      1. 1. levenshtein() example
    6. Additional Tips from Fellow Developers
  28. PHP localeconv() Function
    1. What does localeconv() do?
    2. PHP localeconv() Syntax
    3. PHP localeconv() Parameters
    4. PHP localeconv() Return Value
    5. PHP localeconv() Working Examples
      1. 1. localeconv() example
  29. PHP ltrim() Function
    1. What does ltrim() do?
    2. PHP ltrim() Syntax
    3. PHP ltrim() Parameters
    4. PHP ltrim() Return Value
    5. PHP ltrim() Working Examples
      1. 1. Usage example of ltrim()
    6. Additional Tips from Fellow Developers
  30. PHP md5() Function
    1. What does md5() do?
    2. PHP md5() Syntax
    3. PHP md5() Parameters
    4. PHP md5() Return Value
    5. PHP md5() Working Examples
      1. 1. A md5() example
    6. Important Points about PHP md5() Function
    7. Additional Tips from Fellow Developers
  31. PHP md5_file() Function
    1. What does md5_file() do?
    2. PHP md5_file() Syntax
    3. PHP md5_file() Parameters
    4. PHP md5_file() Return Value
    5. PHP md5_file() Working Examples
      1. 1. Usage example of md5_file()
    6. Changelog for PHP md5_file() Function
    7. Additional Tips from Fellow Developers
  32. PHP metaphone() Function
    1. What does metaphone() do?
    2. PHP metaphone() Syntax
    3. PHP metaphone() Parameters
    4. PHP metaphone() Return Value
    5. PHP metaphone() Working Examples
      1. 1. metaphone() basic example
      2. 2. Using the phonemes parameter
    6. Additional Tips from Fellow Developers
  33. PHP money_format() Function
    1. What does money_format() do?
    2. PHP money_format() Syntax
    3. PHP money_format() Parameters
    4. PHP money_format() Return Value
    5. PHP money_format() Working Examples
      1. 1. money_format() Example
    6. Important Points about PHP money_format() Function
    7. Additional Tips from Fellow Developers
  34. PHP nl2br() Function
    1. What does nl2br() do?
    2. PHP nl2br() Syntax
    3. PHP nl2br() Parameters
    4. PHP nl2br() Return Value
    5. PHP nl2br() Working Examples
      1. 1. Using nl2br()
      2. 2. Generating valid HTML markup using the is_xhtml parameter
      3. 3. Various newline separators
    6. Changelog for PHP nl2br() Function
    7. Additional Tips from Fellow Developers
  35. PHP nl_langinfo() Function
    1. What does nl_langinfo() do?
    2. PHP nl_langinfo() Syntax
    3. PHP nl_langinfo() Parameters
    4. PHP nl_langinfo() Return Value
  36. PHP number_format() Function
    1. What does number_format() do?
    2. PHP number_format() Syntax
    3. PHP number_format() Parameters
    4. PHP number_format() Return Value
    5. PHP number_format() Working Examples
      1. 1. number_format() Example
    6. Changelog for PHP number_format() Function
    7. Additional Tips from Fellow Developers
  37. PHP ord() Function
    1. What does ord() do?
    2. PHP ord() Syntax
    3. PHP ord() Parameters
    4. PHP ord() Return Value
    5. PHP ord() Working Examples
      1. 1. ord() example
      2. 2. Examining the individual bytes of a UTF-8 string
    6. Additional Tips from Fellow Developers
  38. PHP parse_str() Function
    1. What does parse_str() do?
    2. PHP parse_str() Syntax
    3. PHP parse_str() Parameters
    4. PHP parse_str() Return Value
    5. PHP parse_str() Working Examples
      1. 1. Using parse_str()
      2. 2. parse_str() name mangling
    6. Changelog for PHP parse_str() Function
    7. Important Points about PHP parse_str() Function
    8. Additional Tips from Fellow Developers
  39. PHP print() Function
    1. What does print() do?
    2. PHP print() Syntax
    3. PHP print() Parameters
    4. PHP print() Return Value
    5. PHP print() Working Examples
      1. 1. print examples
    6. Additional Tips from Fellow Developers
  40. PHP printf() Function
    1. What does printf() do?
    2. PHP printf() Syntax
    3. PHP printf() Parameters
    4. PHP printf() Return Value
    5. PHP printf() Working Examples
      1. 1. printf(): various examples
      2. 2. printf(): string specifiers
    6. Important Points about PHP printf() Function
  41. PHP quoted_printable_decode() Function
    1. What does quoted_printable_decode() do?
    2. PHP quoted_printable_decode() Syntax
    3. PHP quoted_printable_decode() Parameters
    4. PHP quoted_printable_decode() Return Value
  42. PHP quoted_printable_encode() Function
    1. What does quoted_printable_encode() do?
    2. PHP quoted_printable_encode() Syntax
    3. PHP quoted_printable_encode() Parameters
    4. PHP quoted_printable_encode() Return Value
  43. PHP quotemeta() Function
    1. What does quotemeta() do?
    2. PHP quotemeta() Syntax
    3. PHP quotemeta() Parameters
    4. PHP quotemeta() Return Value
  44. PHP rtrim() Function
    1. What does rtrim() do?
    2. PHP rtrim() Syntax
    3. PHP rtrim() Parameters
    4. PHP rtrim() Return Value
    5. PHP rtrim() Working Examples
      1. 1. Usage example of rtrim()
    6. Additional Tips from Fellow Developers
  45. PHP setlocale() Function
    1. What does setlocale() do?
    2. PHP setlocale() Syntax
    3. PHP setlocale() Parameters
    4. PHP setlocale() Return Value
    5. PHP setlocale() Working Examples
      1. 1. setlocale() Examples
      2. 2. setlocale() Examples for Windows
    6. Changelog for PHP setlocale() Function
    7. Important Points about PHP setlocale() Function
    8. Additional Tips from Fellow Developers
  46. PHP sha1() Function
    1. What does sha1() do?
    2. PHP sha1() Syntax
    3. PHP sha1() Parameters
    4. PHP sha1() Return Value
    5. PHP sha1() Working Examples
      1. 1. A sha1() example
    6. Important Points about PHP sha1() Function
    7. Additional Tips from Fellow Developers
  47. PHP sha1_file() Function
    1. What does sha1_file() do?
    2. PHP sha1_file() Syntax
    3. PHP sha1_file() Parameters
    4. PHP sha1_file() Return Value
    5. PHP sha1_file() Working Examples
      1. 1. sha1_file() example
    6. Changelog for PHP sha1_file() Function
    7. Additional Tips from Fellow Developers
  48. PHP similar_text() Function
    1. What does similar_text() do?
    2. PHP similar_text() Syntax
    3. PHP similar_text() Parameters
    4. PHP similar_text() Return Value
    5. PHP similar_text() Working Examples
      1. 1. similar_text() argument swapping example
    6. Important Points about PHP similar_text() Function
    7. Additional Tips from Fellow Developers
  49. PHP soundex() Function
    1. What does soundex() do?
    2. PHP soundex() Syntax
    3. PHP soundex() Parameters
    4. PHP soundex() Return Value
    5. PHP soundex() Working Examples
      1. 1. Soundex Examples
    6. Additional Tips from Fellow Developers
  50. PHP sprintf() Function
    1. What does sprintf() do?
    2. PHP sprintf() Syntax
    3. PHP sprintf() Parameters
    4. PHP sprintf() Return Value
    5. PHP sprintf() Working Examples
      1. 1. Argument swapping
      2. 2. Specifying padding character
      3. 3. Position specifier with other specifiers
      4. 4. sprintf(): zero-padded integers
      5. 5. sprintf(): formatting currency
      6. 6. sprintf(): scientific notation
    6. Important Points about PHP sprintf() Function
    7. Additional Tips from Fellow Developers
  51. PHP sscanf() Function
    1. What does sscanf() do?
    2. PHP sscanf() Syntax
    3. PHP sscanf() Parameters
    4. PHP sscanf() Return Value
    5. PHP sscanf() Working Examples
      1. 1. sscanf() Example
      2. 2. sscanf() – using optional parameters
    6. Additional Tips from Fellow Developers
  52. PHP str_getcsv() Function
    1. What does str_getcsv() do?
    2. PHP str_getcsv() Syntax
    3. PHP str_getcsv() Parameters
    4. PHP str_getcsv() Return Value
    5. Changelog for PHP str_getcsv() Function
    6. Important Points about PHP str_getcsv() Function
    7. Additional Tips from Fellow Developers
  53. PHP str_ireplace() Function
    1. What does str_ireplace() do?
    2. PHP str_ireplace() Syntax
    3. PHP str_ireplace() Parameters
    4. PHP str_ireplace() Return Value
    5. PHP str_ireplace() Working Examples
      1. 1. str_ireplace() example
    6. Important Points about PHP str_ireplace() Function
    7. Additional Tips from Fellow Developers
  54. PHP str_pad() Function
    1. What does str_pad() do?
    2. PHP str_pad() Syntax
    3. PHP str_pad() Parameters
    4. PHP str_pad() Return Value
    5. PHP str_pad() Working Examples
      1. 1. str_pad() example
    6. Important Points about PHP str_pad() Function
    7. Additional Tips from Fellow Developers
  55. PHP str_repeat() Function
    1. What does str_repeat() do?
    2. PHP str_repeat() Syntax
    3. PHP str_repeat() Parameters
    4. PHP str_repeat() Return Value
    5. PHP str_repeat() Working Examples
      1. 1. str_repeat() example
    6. Additional Tips from Fellow Developers
  56. PHP str_replace() Function
    1. What does str_replace() do?
    2. PHP str_replace() Syntax
    3. PHP str_replace() Parameters
    4. PHP str_replace() Return Value
    5. PHP str_replace() Working Examples
      1. 1. Basic str_replace() examples
      2. 2. Examples of potential str_replace() gotchas
    6. Important Points about PHP str_replace() Function
    7. Additional Tips from Fellow Developers
  57. PHP str_rot13() Function
    1. What does str_rot13() do?
    2. PHP str_rot13() Syntax
    3. PHP str_rot13() Parameters
    4. PHP str_rot13() Return Value
    5. PHP str_rot13() Working Examples
      1. 1. str_rot13() example
    6. Additional Tips from Fellow Developers
  58. PHP str_shuffle() Function
    1. What does str_shuffle() do?
    2. PHP str_shuffle() Syntax
    3. PHP str_shuffle() Parameters
    4. PHP str_shuffle() Return Value
    5. PHP str_shuffle() Working Examples
      1. 1. str_shuffle() example
    6. Changelog for PHP str_shuffle() Function
    7. Important Points about PHP str_shuffle() Function
    8. Additional Tips from Fellow Developers
  59. PHP str_split() Function
    1. What does str_split() do?
    2. PHP str_split() Syntax
    3. PHP str_split() Parameters
    4. PHP str_split() Return Value
    5. PHP str_split() Working Examples
      1. 1. Example uses of str_split()
    6. Important Points about PHP str_split() Function
    7. Additional Tips from Fellow Developers
  60. PHP str_word_count() Function
    1. What does str_word_count() do?
    2. PHP str_word_count() Syntax
    3. PHP str_word_count() Parameters
    4. PHP str_word_count() Return Value
    5. PHP str_word_count() Working Examples
      1. 1. A str_word_count() example
    6. Changelog for PHP str_word_count() Function
    7. Additional Tips from Fellow Developers
  61. PHP strcasecmp() Function
    1. What does strcasecmp() do?
    2. PHP strcasecmp() Syntax
    3. PHP strcasecmp() Parameters
    4. PHP strcasecmp() Return Value
    5. PHP strcasecmp() Working Examples
      1. 1. strcasecmp() example
    6. Additional Tips from Fellow Developers
  62. PHP strchr() Function
    1. What does strchr() do?
    2. PHP strchr() Syntax
    3. PHP strchr() Parameters
  63. PHP strcmp() Function
    1. What does strcmp() do?
    2. PHP strcmp() Syntax
    3. PHP strcmp() Parameters
    4. PHP strcmp() Return Value
    5. PHP strcmp() Working Examples
      1. 1. strcmp() example
    6. Additional Tips from Fellow Developers
  64. PHP strcoll() Function
    1. What does strcoll() do?
    2. PHP strcoll() Syntax
    3. PHP strcoll() Parameters
    4. PHP strcoll() Return Value
  65. PHP strcspn() Function
    1. What does strcspn() do?
    2. PHP strcspn() Syntax
    3. PHP strcspn() Parameters
    4. PHP strcspn() Return Value
    5. PHP strcspn() Working Examples
      1. 1. strcspn() example
    6. Important Points about PHP strcspn() Function
  66. PHP strip_tags() Function
    1. What does strip_tags() do?
    2. PHP strip_tags() Syntax
    3. PHP strip_tags() Parameters
    4. PHP strip_tags() Return Value
    5. PHP strip_tags() Working Examples
      1. 1. strip_tags() example
    6. Changelog for PHP strip_tags() Function
    7. Important Points about PHP strip_tags() Function
    8. Additional Tips from Fellow Developers
  67. PHP stripcslashes() Function
    1. What does stripcslashes() do?
    2. PHP stripcslashes() Syntax
    3. PHP stripcslashes() Parameters
    4. PHP stripcslashes() Return Value
  68. PHP stripos() Function
    1. What does stripos() do?
    2. PHP stripos() Syntax
    3. PHP stripos() Parameters
    4. PHP stripos() Return Value
    5. PHP stripos() Working Examples
      1. 1. stripos() examples
    6. Changelog for PHP stripos() Function
    7. Important Points about PHP stripos() Function
    8. Additional Tips from Fellow Developers
  69. PHP stripslashes() Function
    1. What does stripslashes() do?
    2. PHP stripslashes() Syntax
    3. PHP stripslashes() Parameters
    4. PHP stripslashes() Return Value
    5. PHP stripslashes() Working Examples
      1. 1. A stripslashes() example
      2. 2. Using stripslashes() on an array
    6. Important Points about PHP stripslashes() Function
    7. Additional Tips from Fellow Developers
  70. PHP stristr() Function
    1. What does stristr() do?
    2. PHP stristr() Syntax
    3. PHP stristr() Parameters
    4. PHP stristr() Return Value
    5. PHP stristr() Working Examples
      1. 1. stristr() example
      2. 2. Testing if a string is found or not
      3. 3. Using a non “string” needle
    6. Changelog for PHP stristr() Function
    7. Additional Tips from Fellow Developers
  71. PHP strlen() Function
    1. What does strlen() do?
    2. PHP strlen() Syntax
    3. PHP strlen() Parameters
    4. PHP strlen() Return Value
    5. PHP strlen() Working Examples
      1. 1. A strlen() example
    6. Changelog for PHP strlen() Function
    7. Important Points about PHP strlen() Function
    8. Additional Tips from Fellow Developers
  72. PHP strnatcasecmp() Function
    1. What does strnatcasecmp() do?
    2. PHP strnatcasecmp() Syntax
    3. PHP strnatcasecmp() Parameters
    4. PHP strnatcasecmp() Return Value
  73. PHP strnatcmp() Function
    1. What does strnatcmp() do?
    2. PHP strnatcmp() Syntax
    3. PHP strnatcmp() Parameters
    4. PHP strnatcmp() Return Value
  74. PHP strncasecmp() Function
    1. What does strncasecmp() do?
    2. PHP strncasecmp() Syntax
    3. PHP strncasecmp() Parameters
    4. PHP strncasecmp() Return Value
  75. PHP strncmp() Function
    1. What does strncmp() do?
    2. PHP strncmp() Syntax
    3. PHP strncmp() Parameters
    4. PHP strncmp() Return Value
  76. PHP strpbrk() Function
    1. What does strpbrk() do?
    2. PHP strpbrk() Syntax
    3. PHP strpbrk() Parameters
    4. PHP strpbrk() Return Value
    5. PHP strpbrk() Working Examples
      1. 1. strpbrk() example
    6. Additional Tips from Fellow Developers
  77. PHP strpos() Function
    1. What does strpos() do?
    2. PHP strpos() Syntax
    3. PHP strpos() Parameters
    4. PHP strpos() Return Value
    5. PHP strpos() Working Examples
      1. 1. Using ===
      2. 2. Using !==
      3. 3. Using an offset
    6. Changelog for PHP strpos() Function
    7. Important Points about PHP strpos() Function
    8. Additional Tips from Fellow Developers
  78. PHP strrchr() Function
    1. What does strrchr() do?
    2. PHP strrchr() Syntax
    3. PHP strrchr() Parameters
    4. PHP strrchr() Return Value
    5. PHP strrchr() Working Examples
      1. 1. strrchr() example
    6. Additional Tips from Fellow Developers
  79. PHP strrev() Function
    1. What does strrev() do?
    2. PHP strrev() Syntax
    3. PHP strrev() Parameters
    4. PHP strrev() Return Value
    5. PHP strrev() Working Examples
      1. 1. Reversing a string with strrev()
  80. PHP strripos() Function
    1. What does strripos() do?
    2. PHP strripos() Syntax
    3. PHP strripos() Parameters
    4. PHP strripos() Return Value
    5. PHP strripos() Working Examples
      1. 1. A simple strripos() example
    6. Important Points about PHP strripos() Function
  81. PHP strrpos() Function
    1. What does strrpos() do?
    2. PHP strrpos() Syntax
    3. PHP strrpos() Parameters
    4. PHP strrpos() Return Value
    5. PHP strrpos() Working Examples
      1. 1. Checking if a needle is in the haystack
      2. 2. Searching with offsets
    6. Important Points about PHP strrpos() Function
    7. Additional Tips from Fellow Developers
  82. PHP strspn() Function
    1. What does strspn() do?
    2. PHP strspn() Syntax
    3. PHP strspn() Parameters
    4. PHP strspn() Return Value
    5. PHP strspn() Working Examples
      1. 1. strspn() example
    6. Important Points about PHP strspn() Function
    7. Additional Tips from Fellow Developers
  83. PHP strstr() Function
    1. What does strstr() do?
    2. PHP strstr() Syntax
    3. PHP strstr() Parameters
    4. PHP strstr() Return Value
    5. PHP strstr() Working Examples
      1. 1. strstr() example
    6. Changelog for PHP strstr() Function
    7. Important Points about PHP strstr() Function
    8. Additional Tips from Fellow Developers
  84. PHP strtok() Function
    1. What does strtok() do?
    2. PHP strtok() Syntax
    3. PHP strtok() Parameters
    4. PHP strtok() Return Value
    5. PHP strtok() Working Examples
      1. 1. strtok() example
      2. 2. strtok() behavior on empty part found
    6. Important Points about PHP strtok() Function
    7. Additional Tips from Fellow Developers
  85. PHP strtolower() Function
    1. What does strtolower() do?
    2. PHP strtolower() Syntax
    3. PHP strtolower() Parameters
    4. PHP strtolower() Return Value
    5. PHP strtolower() Working Examples
      1. 1. strtolower() example
    6. Additional Tips from Fellow Developers
  86. PHP strtoupper() Function
    1. What does strtoupper() do?
    2. PHP strtoupper() Syntax
    3. PHP strtoupper() Parameters
    4. PHP strtoupper() Return Value
    5. PHP strtoupper() Working Examples
      1. 1. strtoupper() example
    6. Additional Tips from Fellow Developers
  87. PHP strtr() Function
    1. What does strtr() do?
    2. PHP strtr() Syntax
    3. PHP strtr() Parameters
    4. PHP strtr() Return Value
    5. PHP strtr() Working Examples
      1. 1. strtr() example
      2. 2. strtr() example with two arguments
      3. 3. strtr() behavior comparison
    6. Additional Tips from Fellow Developers
  88. PHP substr() Function
    1. What does substr() do?
    2. PHP substr() Syntax
    3. PHP substr() Parameters
    4. PHP substr() Return Value
    5. PHP substr() Working Examples
      1. 1. Using a negative start
      2. 2. Using a negative length
      3. 3. Basic substr() usage
      4. 4. substr() casting behaviour
    6. Changelog for PHP substr() Function
    7. Additional Tips from Fellow Developers
  89. PHP substr_compare() Function
    1. What does substr_compare() do?
    2. PHP substr_compare() Syntax
    3. PHP substr_compare() Parameters
    4. PHP substr_compare() Return Value
    5. PHP substr_compare() Working Examples
      1. 1. A substr_compare() example
    6. Changelog for PHP substr_compare() Function
    7. Additional Tips from Fellow Developers
  90. PHP substr_count() Function
    1. What does substr_count() do?
    2. PHP substr_count() Syntax
    3. PHP substr_count() Parameters
    4. PHP substr_count() Return Value
    5. PHP substr_count() Working Examples
      1. 1. A substr_count() example
    6. Changelog for PHP substr_count() Function
    7. Important Points about PHP substr_count() Function
    8. Additional Tips from Fellow Developers
  91. PHP substr_replace() Function
    1. What does substr_replace() do?
    2. PHP substr_replace() Syntax
    3. PHP substr_replace() Parameters
    4. PHP substr_replace() Return Value
    5. PHP substr_replace() Working Examples
      1. 1. Simple substr_replace() examples
      2. 2. Using substr_replace() to replace multiple strings at once
    6. Additional Tips from Fellow Developers
  92. PHP trim() Function
    1. What does trim() do?
    2. PHP trim() Syntax
    3. PHP trim() Parameters
    4. PHP trim() Return Value
    5. PHP trim() Working Examples
      1. 1. Usage example of trim()
      2. 2. Trimming array values with trim()
    6. Important Points about PHP trim() Function
    7. Additional Tips from Fellow Developers
  93. PHP ucfirst() Function
    1. What does ucfirst() do?
    2. PHP ucfirst() Syntax
    3. PHP ucfirst() Parameters
    4. PHP ucfirst() Return Value
    5. PHP ucfirst() Working Examples
      1. 1. ucfirst() example
    6. Additional Tips from Fellow Developers
  94. PHP ucwords() Function
    1. What does ucwords() do?
    2. PHP ucwords() Syntax
    3. PHP ucwords() Parameters
    4. PHP ucwords() Return Value
    5. PHP ucwords() Working Examples
      1. 1. ucwords() example
      2. 2. ucwords() example with custom delimiter
    6. Changelog for PHP ucwords() Function
    7. Additional Tips from Fellow Developers
  95. PHP vfprintf() Function
    1. What does vfprintf() do?
    2. PHP vfprintf() Syntax
    3. PHP vfprintf() Parameters
    4. PHP vfprintf() Return Value
    5. PHP vfprintf() Working Examples
      1. 1. vfprintf(): zero-padded integers
    6. Important Points about PHP vfprintf() Function
  96. PHP vprintf() Function
    1. What does vprintf() do?
    2. PHP vprintf() Syntax
    3. PHP vprintf() Parameters
    4. PHP vprintf() Return Value
    5. PHP vprintf() Working Examples
      1. 1. vprintf(): zero-padded integers
    6. Important Points about PHP vprintf() Function
  97. PHP vsprintf() Function
    1. What does vsprintf() do?
    2. PHP vsprintf() Syntax
    3. PHP vsprintf() Parameters
    4. PHP vsprintf() Return Value
    5. PHP vsprintf() Working Examples
      1. 1. vsprintf(): zero-padded integers
    6. Important Points about PHP vsprintf() Function
    7. Additional Tips from Fellow Developers
  98. PHP wordwrap() Function
    1. What does wordwrap() do?
    2. PHP wordwrap() Syntax
    3. PHP wordwrap() Parameters
    4. PHP wordwrap() Return Value
    5. PHP wordwrap() Working Examples
      1. 1. wordwrap() example
      2. 2. wordwrap() example
      3. 3. wordwrap() example
    6. Additional Tips from Fellow Developers

PHP addcslashes() Function

What does addcslashes() do?

The PHP addcslashes() function will give you a string with backslashes before characters that are listed in charlist parameter.

PHP addcslashes() Syntax

 addcslashes ( string $str , string $charlist ) : string

PHP addcslashes() Parameters

  1. str — The string to be escaped.

  2. charlist — A list of characters to be escaped. If charlist contains characters \n, \r etc., they are converted in C-like style, while other non-alphanumeric characters with ASCII codes lower than 32 and higher than 126 converted to octal representation.

PHP addcslashes() Return Value

The PHP addcslashes() function returns the escaped string.

PHP addcslashes() Working Examples

1. addcslashes() example

<?php
$escaped = addcslashes($not_escaped, "\0..\37!@\177..\377");
?>

Changelog for PHP addcslashes() Function

5.2.5 — The escape sequences \v and \f were added.

PHP addslashes() Function

What does addslashes() do?

The PHP addslashes() function will give you a string with backslashes added before characters that need to be escaped. These characters are:

PHP addslashes() Syntax

 addslashes ( string $str ) : string

PHP addslashes() Parameters

  1. str — The string to be escaped.

PHP addslashes() Return Value

The PHP addslashes() function returns the escaped string.

PHP addslashes() Working Examples

1. An addslashes() example

<?php
$str = "Is your name O'Reilly?";
// Outputs: Is your name O\'Reilly?
echo addslashes($str);
?>

Additional Tips from Fellow Developers

Contributed By: wyattstorch42

@ mark at hagers dot demon dot nl :
You shouldn't use str_replace() for this. Use a function like htmlentities(), which will properly encode all user input for fields. That way, it will also work if the user types &, <, >, etc.

Contributed By: roysimke

Never use addslashes function to escape values you are going to send to mysql. use mysql_real_escape_string or pg_escape at least if you are not using prepared queries yet.
keep in mind that single quote is not the only special character that can break your sql query. and quotes are the only thing which addslashes care.

Contributed By: svenr

To output a PHP variable to Javascript, use json_encode().
<?php
$var = "He said \"Hello O'Reilly\" & disappeared.\nNext line...";
echo "alert(".json_encode($var).");\n";
?>
Output:
alert("He said \"Hello O'Reilly\" & disappeared.\nNext line...") ;

Contributed By: mark

I was stumped for a long time by the fact that even when using addslashes and stripslashes explicitly on the field values double quotes (") still didn't seem to show up in strings read from a database. Until I looked at the source, and realised that the field value is just truncated at the first occurrence of a double quote. the remainder of the string is there (in the source), but is ignored when the form is displayed and submitted.
This can easily be solved by replacing double quotes with "&quot;" when building the form. like this:
$fld_value =  str_replace ( "\"", "&quot;", $src_string ) ;
The reverse replacement after the form submission is not necessary.

PHP bin2hex() Function

What does bin2hex() do?

The PHP bin2hex() function will convert binary data into hexadecimal representation.

PHP bin2hex() Syntax

 bin2hex ( string $str ) : string

PHP bin2hex() Parameters

  1. str — A string.

PHP bin2hex() Return Value

The PHP bin2hex() function returns the hexadecimal representation of the given string.

Additional Tips from Fellow Developers

Contributed By: tehjosh

This function is for converting binary data into a hexadecimal string representation.  This function is not for converting strings representing binary digits into hexadecimal.  If you want that functionality, you can simply do this:
<?php
$binary = "11111001";
$hex = dechex(bindec($binary));
echo $hex;
?>
This would output "f9".  Just remember that there is a very big difference between binary data and a string representation of binary.

PHP chop() Function

What does chop() do?

The PHP chop() function will this function is an alias of: rtrim().

PHP chop() Syntax

PHP chop() Parameters

    This function does not accept any parameters.

    Important Points about PHP chop() Function

    1. chop() is different than the Perl chop() function, which removes the last character in the string.

    Additional Tips from Fellow Developers

    Contributed By: Kubo2

    Rather use rtrim(). Usage of chop() is not very clear nor consistent for people reading the code after you.

    Contributed By: JumpIfBelow

    If you are searching for a function that does the same trick as chop in PERL, then you should just do the following code:
    <?php
       $str = substr($str, 0, -1);
    ?>
    The question is: why isn't chop() an alias of the code above, rather than something which will trap developpers?

    PHP chr() Function

    What does chr() do?

    The PHP chr() function will generate a single-byte string from a number.

    PHP chr() Syntax

     chr ( int $bytevalue ) : string

    PHP chr() Parameters

    1. bytevalue — An integer between 0 and 255.

    PHP chr() Return Value

    The PHP chr() function returns a single-character string containing the specified byte.

    PHP chr() Working Examples

    1. chr() example

    <?php
    // Assumes the string will be used as ASCII or an ASCII-compatible encoding
    $str = "The string ends in escape: ";
    $str .= chr(27); /* add an escape character at the end of $str */
    /* Often this is more useful */
    $str = sprintf("The string ends in escape: %c", 27);
    ?>

    2. Overflow behavior

    <?php
    echo chr(-159), chr(833), PHP_EOL;
    ?>

    Output of the above code:

    aA

    3. Building a UTF-8 string from individual bytes

    <?php
    declare(encoding='UTF-8');
    $str = chr(240) . chr(159) . chr(144) . chr(152);
    echo $str;
    ?>

    Output of the above code:


    🐘

    Additional Tips from Fellow Developers

    Contributed By: perrodin

    Note that if the number is higher than 256, it will return the number mod 256.
    For example :
    chr(321)=A because A=65(256)

    PHP chunk_split() Function

    What does chunk_split() do?

    The PHP chunk_split() function will can be used to split a string into smaller chunks which is useful for e.g. converting base64_encode() output to match RFC 2045 semantics. It inserts end every chunklen characters.

    PHP chunk_split() Syntax

     chunk_split ( string $body [, int $chunklen = 76 [, string $end = "\r\n" ]] ) : string

    PHP chunk_split() Parameters

    1. body — The string to be chunked.

    2. chunklen — The chunk length.

    3. end — The line ending sequence.

    PHP chunk_split() Return Value

    The PHP chunk_split() function returns the chunked string.

    PHP chunk_split() Working Examples

    1. chunk_split() example

    <?php
    // format $data using RFC 2045 semantics
    $new_string = chunk_split(base64_encode($data));
    ?>

    Additional Tips from Fellow Developers

    Contributed By:

    An alternative for unicode strings;
    <?php
    function chunk_split_unicode($str, $l = 76, $e = "\r\n") {
        $tmp = array_chunk(
            preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $l);
        $str = "";
        foreach ($tmp as $t) {
            $str .= join("", $t) . $e;
        }
        return $str;
    }
    $str = "Yarım kilo çay, yarım kilo şeker";
    echo chunk_split($str, 4) ."\n";
    echo chunk_split_unicode($str, 4);
    ?>
    Yar�
    �m k
    ilo 
    çay
    , ya
    rım
     kil
    o ş
    eker
    Yarı
    m ki
    lo ç
    ay, 
    yarı
    m ki
    lo ş
    eker

    PHP convert_cyr_string() Function

    What does convert_cyr_string() do?

    The PHP convert_cyr_string() function will convert from one Cyrillic character set to another.

    PHP convert_cyr_string() Syntax

     convert_cyr_string ( string $str , string $from , string $to ) : string

    PHP convert_cyr_string() Parameters

    1. str — The string to be converted.

    2. from — The source Cyrillic character set, as a single character.

    3. to — The target Cyrillic character set, as a single character.

    PHP convert_cyr_string() Return Value

    The PHP convert_cyr_string() function returns the converted string.

    PHP convert_uudecode() Function

    What does convert_uudecode() do?

    The PHP convert_uudecode() function will convert_uudecode() decodes a uuencoded string.

    PHP convert_uudecode() Syntax

     convert_uudecode ( string $data ) : string

    PHP convert_uudecode() Parameters

    1. data — The uuencoded data.

    PHP convert_uudecode() Return Value

    The PHP convert_uudecode() function returns the decoded data as a string or FALSE on failure.

    PHP convert_uudecode() Working Examples

    1. convert_uudecode() example

    <?php
    echo convert_uudecode("+22!L;W9E(%!(4\"$`\n`");
    ?>

    Output of the above code:

    I love PHP!

    PHP convert_uuencode() Function

    What does convert_uuencode() do?

    The PHP convert_uuencode() function will convert_uuencode() encodes a string using the uuencode algorithm.

    PHP convert_uuencode() Syntax

     convert_uuencode ( string $data ) : string

    PHP convert_uuencode() Parameters

    1. data — The data to be encoded.

    PHP convert_uuencode() Return Value

    The PHP convert_uuencode() function returns the uuencoded data or FALSE on failure.

    PHP convert_uuencode() Working Examples

    1. convert_uuencode() example

    <?php
    $some_string = "test\ntext text\r\n";
    echo convert_uuencode($some_string);
    ?>

    Output of the above code:

    0=&5S=`IT97AT('1E>'0-"@``
    `

    Additional Tips from Fellow Developers

    Contributed By: root

    @Craig's note: base64_encode() is better suited for that. In fact, it produces smaller output and operates slightly faster. I did a little benchmark -- here are my findings:
    File: JPG, 631614 bytes
    == Base64 ==
    execution time: 0.0039639472961426 secs
    output length: 842152
    == UUencode ==
    execution time: 0.004105806350708 secs
    output length: 870226

    PHP count_chars() Function

    What does count_chars() do?

    The PHP count_chars() function will give you

    PHP count_chars() Syntax

     count_chars ( string $string [, int $mode = 0 ] ) : mixed

    PHP count_chars() Parameters

    1. string — The examined string.

    2. mode — See return values.

    PHP count_chars() Return Value

    The PHP count_chars() function returns one of the following:

    PHP count_chars() Working Examples

    1. count_chars() example

    <?php
    $data = "Two Ts and one F.";
    foreach (count_chars($data, 1) as $i => $val) {
       echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n";
    }
    ?>

    Output of the above code:

    There were 4 instance(s) of " " in the string.
    There were 1 instance(s) of "." in the string.
    There were 1 instance(s) of "F" in the string.
    There were 2 instance(s) of "T" in the string.
    There were 1 instance(s) of "a" in the string.
    There were 1 instance(s) of "d" in the string.
    There were 1 instance(s) of "e" in the string.
    There were 2 instance(s) of "n" in the string.
    There were 2 instance(s) of "o" in the string.
    There were 1 instance(s) of "s" in the string.
    There were 1 instance(s) of "w" in the string.

    Additional Tips from Fellow Developers

    Contributed By: marcus33cz

    If you have problems using count_chars with a multibyte string, you can change the page encoding. Alternatively, you can also use this mb_count_chars version of the function. Basically it is mode "1" of the original function.
    <?php
    /**
     * Counts character occurences in a multibyte string
     * @param string $input UTF-8 data
     * @return array associative array of characters.
     */
    function mb_count_chars($input) {
        $l = mb_strlen($input, 'UTF-8');
        $unique = array();
        for($i = 0; $i < $l; $i++) {
            $char = mb_substr($input, $i, 1, 'UTF-8');
            if(!array_key_exists($char, $unique))
                $unique[$char] = 0;
            $unique[$char]++;
        }
        return $unique;
    }
    $input = "Let's try some Greek letters: αααααΕεΙιΜμΨψ, Russian: ЙЙЫЫЩН, Czech: ěščřžýáíé";
    print_r( mb_count_chars($input) ); 
    //returns: Array ( [L] => 1 [e] => 7 [t] => 4 ['] => 1 [s] => 5 [ ] => 9 [r] => 3 [y] => 1 [o] => 1 [m] => 1 [G] => 1 [k] => 1 [l] => 1 [:] => 3 [α] => 5 [Ε] => 1 [ε] => 1 [Ι] => 1 [ι] => 1 [Μ] => 1 [μ] => 1 [Ψ] => 1 [ψ] => 1 [,] => 2 [R] => 1 [u] => 1 [i] => 1 [a] => 1 [n] => 1 [Й] => 2 [Ы] => 2 [Щ] => 1 [Н] => 1 [C] => 1 [z] => 1 [c] => 1 [h] => 1 [ě] => 1 [š] => 1 [č] => 1 [ř] => 1 [ž] => 1 [ý] => 1 [á] => 1 [í] => 1 [é] => 1 )
    ?>

    PHP crc32() Function

    What does crc32() do?

    The PHP crc32() function will calculates the crc32 polynomial of a string.

    PHP crc32() Syntax

     crc32 ( string $str ) : int

    PHP crc32() Parameters

    1. str — The data.

    PHP crc32() Return Value

    The PHP crc32() function returns the crc32 checksum of str as an integer.

    PHP crc32() Working Examples

    1. Displaying a crc32 checksum

    <?php
    $checksum = crc32("The quick brown fox jumped over the lazy dog.");
    printf("%u\n", $checksum);
    ?>

    Important Points about PHP crc32() Function

    1. Because PHP’s integer type is signed many crc32 checksums will result in negative integers on 32bit platforms. On 64bit installations all crc32() results will be positive integers though.

    2. So you need to use the “%u” formatter of sprintf() or printf() to get the string representation of the unsigned crc32() checksum in decimal format.

    3. For a hexadecimal representation of the checksum you can either use the “%x” formatter of sprintf() or printf() or the dechex() conversion functions, both of these also take care of converting the crc32() result to an unsigned integer.

    4. Having 64bit installations also return negative integers for higher result values was considered but would break the hexadecimal conversion as negatives would get an extra 0xFFFFFFFF######## offset then. As hexadecimal representation seems to be the most common use case we decided to not break this even if it breaks direct decimal comparisons in about 50% of the cases when moving from 32 to 64bits.

    5. In retrospect having the function return an integer maybe wasn’t the best idea and returning a hex string representation right away (as e.g. md5() does) might have been a better plan to begin with.

    6. For a more portable solution you may also consider the generic hash(). hash("crc32b", $str) will return the same string as str_pad(dechex(crc32($str)), 8, '0', STR_PAD_LEFT).

    PHP crypt() Function

    What does crypt() do?

    The PHP crypt() function will give you a hashed string using the standard Unix DES-based algorithm or alternative algorithms that may be available on the system.

    PHP crypt() Syntax

     crypt ( string $str [, string $salt ] ) : string

    PHP crypt() Parameters

    1. str — The string to be hashed.

    2. salt — An optional salt string to base the hashing on. If not provided, the behaviour is defined by the algorithm implementation and can lead to unexpected results.

    PHP crypt() Return Value

    The PHP crypt() function returns the hashed string or a string that is shorter than 13 characters and is guaranteed to differ from the salt on failure.

    PHP crypt() Working Examples

    1. crypt() examples

    <?php
    $hashed_password = crypt('mypassword'); // let the salt be automatically generated
    /* You should pass the entire results of crypt() as the salt for comparing a
       password, to avoid problems when different hashing algorithms are used. (As
       it says above, standard DES-based password hashing uses a 2-character salt,
       but MD5-based hashing uses 12.) */
    if (hash_equals($hashed_password, crypt($user_input, $hashed_password))) {
       echo "Password verified!";
    }
    ?>

    2. Using crypt() with htpasswd

    <?php
    // Set the password
    $password = 'mypassword';
    // Get the hash, letting the salt be automatically generated
    $hash = crypt($password);
    ?>

    3. Using crypt() with different hash types

    <?php
    /* These salts are examples only, and should not be used verbatim in your code.
       You should generate a distinct, correctly-formatted salt for each password.
    */
    if (CRYPT_STD_DES == 1) {
        echo 'Standard DES: ' . crypt('rasmuslerdorf', 'rl') . "\n";
    }
    if (CRYPT_EXT_DES == 1) {
        echo 'Extended DES: ' . crypt('rasmuslerdorf', '_J9..rasm') . "\n";
    }
    if (CRYPT_MD5 == 1) {
        echo 'MD5:          ' . crypt('rasmuslerdorf', '$1$rasmusle$') . "\n";
    }
    if (CRYPT_BLOWFISH == 1) {
        echo 'Blowfish:     ' . crypt('rasmuslerdorf', '$2a$07$usesomesillystringforsalt$') . "\n";
    }
    if (CRYPT_SHA256 == 1) {
        echo 'SHA-256:      ' . crypt('rasmuslerdorf', '$5$rounds=5000$usesomesillystringforsalt$') . "\n";
    }
    if (CRYPT_SHA512 == 1) {
        echo 'SHA-512:      ' . crypt('rasmuslerdorf', '$6$rounds=5000$usesomesillystringforsalt$') . "\n";
    }
    ?>

    Output of the above code:

    Standard DES: rl.3StKT.4T8M
    Extended DES: _J9..rasmBYk8r9AiWNc
    MD5: $1$rasmusle$rISCgZzpwk3UhDidwXvin0
    Blowfish: $2a$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi
    SHA-256: $5$rounds=5000$usesomesillystri$KqJWpanXZHKq2BOB43TSaYhEWsQ1Lr5QNyPCDH/Tp.6
    SHA-512: $6$rounds=5000$usesomesillystri$D4IrlXatmP7rx3P3InaxBeoomnAihCKRVQP22JZ6EY47Wc6BkroIuUUBOov1i.S5KPgErtP/EN5mcO.ChWQW21

    Changelog for PHP crypt() Function

    5.6.5 — When the failure string “*0” is given as the salt, “*1” will now be returned for consistency with other crypt implementations. Prior to this version, PHP 5.6 would incorrectly return a DES hash.

    5.6.0 — Raise E_NOTICE security warning if salt is omitted.

    5.5.21 — When the failure string “*0” is given as the salt, “*1” will now be returned for consistency with other crypt implementations. Prior to this version, PHP 5.5 (and earlier branches) would incorrectly return a DES hash.

    5.3.7 — Added $2x$ and $2y$ Blowfish modes to deal with potential high-bit attacks.

    5.3.2 — Added SHA-256 and SHA-512 crypt based on Ulrich Drepper’s » implementation.

    5.3.2 — Fixed Blowfish behaviour on invalid rounds to return “failure” string (“*0” or “*1”), instead of falling back to DES.

    5.3.0 — PHP now contains its own implementation for the MD5 crypt, Standard DES, Extended DES and the Blowfish algorithms and will use that if the system lacks of support for one or more of the algorithms.

    Important Points about PHP crypt() Function

    1. This function is not (yet) binary safe!

    2. As of PHP 5.3.0, PHP contains its own implementation and will use that if the system lacks of support for one or more of the algorithms.

    3. Using the CRYPT_BLOWFISH algorithm, will result in the str parameter being truncated to a maximum length of 72 characters.

    4. When validating passwords, a string comparison function that isn’t vulnerable to timing attacks should be used to compare the output of crypt() to the previously known hash. PHP 5.6 onwards provides hash_equals() for this purpose.

    Additional Tips from Fellow Developers

    Contributed By: bob dot orr

    The #2 comment on this comments page (as of Feb 2015) is 9 years old and recommends phpass.  I have independently security audited this product and, while it continues to be recommended for password security, it is actually insecure and should NOT be used.  It hasn't seen any updates in years (still at v0.3) and there are more recent alternatives such as using the newer built-in PHP password_hash() function that are much better.  Everyone, please take a few moments to confirm what I'm saying is accurate (i.e. review the phpass code for yourself) and then click the down arrow to sink the phpass comment to the bottom.  You'll be increasing security across the Internet by doing so.
    For those who want details:  md5() with microtime() are a fallback position within the source code of phpass.  Instead of terminating, it continues to execute code.  The author's intentions of trying to work everywhere are admirable but, when it comes to application security, that stance actually backfires.  The only correct answer in a security context is to terminate the application rather than fallback to a weak position that can potentially be exploited (usually by forcing that weaker position to happen).

    Contributed By: Marten Jacobs

    As I understand it, blowfish is generally seen a secure hashing algorithm, even for enterprise use (correct me if I'm wrong). Because of this, I created functions to create and check secure password hashes using this algorithm, and using the (also deemed cryptographically secure) openssl_random_pseudo_bytes function to generate the salt.
    <?php
    /*
     * Generate a secure hash for a given password. The cost is passed
     * to the blowfish algorithm. Check the PHP manual page for crypt to
     * find more information about this setting.
     */
    function generate_hash($password, $cost=11){
            /* To generate the salt, first generate enough random bytes. Because
             * base64 returns one character for each 6 bits, the we should generate
             * at least 22*6/8=16.5 bytes, so we generate 17. Then we get the first
             * 22 base64 characters
             */
            $salt=substr(base64_encode(openssl_random_pseudo_bytes(17)),0,22);
            /* As blowfish takes a salt with the alphabet ./A-Za-z0-9 we have to
             * replace any '+' in the base64 string with '.'. We don't have to do
             * anything about the '=', as this only occurs when the b64 string is
             * padded, which is always after the first 22 characters.
             */
            $salt=str_replace("+",".",$salt);
            /* Next, create a string that will be passed to crypt, containing all
             * of the settings, separated by dollar signs
             */
            $param='$'.implode('$',array(
                    "2y", //select the most secure version of blowfish (>=PHP 5.3.7)
                    str_pad($cost,2,"0",STR_PAD_LEFT), //add the cost in two digits
                    $salt //add the salt
            ));
           
            //now do the actual hashing
            return crypt($password,$param);
    }
     
    /*
     * Check the password against a hash generated by the generate_hash
     * function.
     */
    function validate_pw($password, $hash){
            /* Regenerating the with an available hash as the options parameter should
             * produce the same hash if the same password is passed.
             */
            return crypt($password, $hash)==$hash;
    }
    ?>

    PHP echo() Function

    What does echo() do?

    The PHP echo() function will outputs all parameters. No additional newline is appended.

    PHP echo() Syntax

     echo ( string $arg1 [, string $... ] ) : void

    PHP echo() Parameters

    1. arg1 — The parameter to output.

    2. ...

    PHP echo() Return Value

    The PHP echo() function returns d.

    PHP echo() Working Examples

    1. echo examples

    <?php
    echo "Hello World";
    // Strings can either be passed individually as multiple arguments or
    // concatenated together and passed as a single argument
    echo 'This ', 'string ', 'was ', 'made ', 'with multiple parameters.', chr(10);
    echo 'This ' . 'string ' . 'was ' . 'made ' . 'with concatenation.' . "\n";
    // Because echo does not behave like a function, the following code is invalid.
    ($some_var) ? echo 'true' : echo 'false';
    // However, the following examples will work:
    ($some_var) ? print 'true' : print 'false'; // print is also a construct, but
                                                // it behaves like a function, so
                                                // it may be used in this context.
    echo $some_var ? 'true': 'false'; // changing the statement around
    ?>

    PHP explode() Function

    What does explode() do?

    The PHP explode() function will give you an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.

    PHP explode() Syntax

     explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] ) : array

    PHP explode() Parameters

    1. delimiter — The boundary string.

    2. string — The input string.

    3. limit — If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

    PHP explode() Return Value

    The PHP explode() function returns an array of strings created by splitting the string parameter on boundaries formed by the delimiter.

    PHP explode() Working Examples

    1. explode() examples

    <?php
    // Example 1
    $pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
    $pieces = explode(" ", $pizza);
    echo $pieces[0]; // piece1
    echo $pieces[1]; // piece2
    // Example 2
    $data = "foo:*:1023:1000::/home/foo:/bin/sh";
    list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
    echo $user; // foo
    echo $pass; // *
    ?>

    2. explode() return examples

    <?php
    /* 
       A string that doesn't contain the delimiter will simply
       return a one-length array of the original string.
    */
    $input1 = "hello";
    $input2 = "hello,there";
    $input3 = ',';
    var_dump( explode( ',', $input1 ) );
    var_dump( explode( ',', $input2 ) );
    var_dump( explode( ',', $input3 ) );
    ?>

    Output of the above code:

    array(1)
    (
     [0] => string(5) "hello"
    )
    array(2)
    (
     [0] => string(5) "hello"
     [1] => string(5) "there"
    )
    array(2)
    (
     [0] => string(0) ""
     [1] => string(0) ""
    )

    3. limit parameter examples

    <?php
    $str = 'one|two|three|four';
    // positive limit
    print_r(explode('|', $str, 2));
    // negative limit (since PHP 5.1)
    print_r(explode('|', $str, -1));
    ?>

    Output of the above code:

    Array
    (
     [0] => one
     [1] => two|three|four
    )
    Array
    (
     [0] => one
     [1] => two
     [2] => three
    )

    Changelog for PHP explode() Function

    5.1.0 — Support for negative limits was added

    Important Points about PHP explode() Function

    1. Although implode() can, for historical reasons, accept its parameters in either order, explode() cannot. You must ensure that the delimiter argument comes before the string argument.

    Additional Tips from Fellow Developers

    Contributed By: php

    Here is my approach to have exploded output with multiple delimiter. 
    <?php
    //$delimiters has to be array
    //$string has to be array
    function multiexplode ($delimiters,$string) {
        
        $ready = str_replace($delimiters, $delimiters[0], $string);
        $launch = explode($delimiters[0], $ready);
        return  $launch;
    }
    $text = "here is a sample: this text, and this will be exploded. this also | this one too :)";
    $exploded = multiexplode(array(",",".","|",":"),$text);
    print_r($exploded);
    //And output will be like this:
    // Array
    // (
    //    [0] => here is a sample
    //    [1] =>  this text
    //    [2] =>  and this will be exploded
    //    [3] =>  this also 
    //    [4] =>  this one too 
    //    [5] => )
    // )
    ?>

    Contributed By: tiago dot dias

    Beaware splitting empty strings.
    <?php
    $str = "";
    $res = explode(",", $str);
    print_r($res);
    ?>
    If you split an empty string, you get back a one-element array with 0 as the key and an empty string for the value.
    Array
    (
        [0] => 
    )
    To solve this, just use array_filter() without callback. Quoting manual page "If the callback function is not supplied, array_filter() will remove all the entries of input that are equal to FALSE.".
    <?php
    $str = "";
    $res = array_filter(explode(",", $str));
    print_r($res);
    ?>
    Array
    (
    )

    Contributed By:

    The comments to use array_filter() without a callback to remove empty strings from explode's results miss the fact that array_filter will remove all elements that, to quote the manual,  "are equal to FALSE".
    This includes, in particular, the string "0", which is NOT an empty string.
    If you really want to filter out empty strings, use the defining feature of the empty string that it is the only string that has a length of 0. So:
    <?php
    array_filter(explode(':', "1:2::3:0:4"), 'strlen');
    ?>

    Contributed By: eye_syah88

    A simple one line method to explode & trim whitespaces from the exploded elements
    array_map('trim',explode(",",$str));
    example:
    $str="one  ,two  ,       three  ,  four    "; 
    print_r(array_map('trim',explode(",",$str)));
    Output:
    Array ( [0] => one [1] => two [2] => three [3] => four )

    Contributed By: m0gr14

    Here's a function for "multi" exploding a string.
    <?php
    //the function
    //Param 1 has to be an Array
    //Param 2 has to be a String
    function multiexplode ($delimiters,$string) {
        $ary = explode($delimiters[0],$string);
        array_shift($delimiters);
        if($delimiters != NULL) {
            foreach($ary as $key => $val) {
                 $ary[$key] = multiexplode($delimiters, $val);
            }
        }
        return  $ary;
    }
    // Example of use
    $string = "1-2-3|4-5|6:7-8-9-0|1,2:3-4|5";
    $delimiters = Array(",",":","|","-");
    $res = multiexplode($delimiters,$string);
    echo '<pre>';
    print_r($res);
    echo '</pre>';
    //returns
    /*
    Array
    (
        [0] => Array
            (
                [0] => Array
                    (
                        [0] => Array
                            (
                                [0] => 1
                                [1] => 2
                                [2] => 3
                            )
                        [1] => Array
                            (
                                [0] => 4
                                [1] => 5
                            )
                        [2] => Array
                            (
                                [0] => 6
                            )
                    )
                [1] => Array
                    (
                        [0] => Array
                            (
                                [0] => 7
                                [1] => 8
                                [2] => 9
                                [3] => 0
                            )
                        [1] => Array
                            (
                                [0] => 1
                            )
                    )
            )
        [1] => Array
            (
                [0] => Array
                    (
                        [0] => Array
                            (
                                [0] => 2
                            )
                    )
                [1] => Array
                    (
                        [0] => Array
                            (
                                [0] => 3
                                [1] => 4
                            )
                        [1] => Array
                            (
                                [0] => 5
                            )
                    )
            )
    )
    */
    ?>

    Contributed By: Anonymous

    <?php
    // converts pure string into a trimmed keyed array
    function string2KeyedArray($string, $delimiter = ',', $kv = '=>') {
      if ($a = explode($delimiter, $string)) { // create parts
        foreach ($a as $s) { // each part
          if ($s) {
            if ($pos = strpos($s, $kv)) { // key/value delimiter
              $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
            } else { // key delimiter not found
              $ka[] = trim($s);
            }
          }
        }
        return $ka;
      }
    } // string2KeyedArray
    $string = 'a=>1, b=>23   , $a, c=> 45% , true,d => ab c ';
    print_r(string2KeyedArray($string));
    ?>
    Array
    (
      [a] => 1
      [b] => 23
      [0] => $a
      [c] => 45%
      [1] => true
      [d] => ab c
    )

    Contributed By: kkobashi

    Explode does not parse a string by delimiters, in the sense that we expect to find tokens between a starting and ending delimiter, but instead splits a string into parts by using a string as the boundary of each part. Once that boundary is discovered the string is split. Whether or not that boundary is proceeded or superseded by any data is irrelevant since the parts are determined at the point a boundary is discovered. 
     
    For example: 
     
    <?php 
     
    var_dump(explode("/","/")); 
     
    /* 
       Outputs 
     
       array(2) { 
         [0]=> 
         string(0) "" 
         [1]=> 
         string(0) "" 
       } 
    */ 
     
    ?> 
     
    The reason we have two empty strings here is that a boundary is discovered before any data has been collected from the string. The boundary splits the string into two parts even though those parts are empty. 
     
    One way to avoid getting back empty parts (if you don't care for those empty parts) is to use array_filter on the result. 
     
    <?php 
     
    var_dump(array_filter(explode("/","/"))); 
     
    /* 
       Outputs 
     
       array(0) { 
       } 
    */ 
    ?> 
     
    *[This note was edited by googleguy at php dot net for clarity]*

    PHP fprintf() Function

    What does fprintf() do?

    The PHP fprintf() function will write a string produced according to format to the stream resource specified by handle.

    PHP fprintf() Syntax

     fprintf ( resource $handle , string $format [, mixed $... ] ) : int

    PHP fprintf() Parameters

    1. handle — A file system pointer resource that is typically created using fopen().

    2. format — The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result and conversion specifications, each of which results in fetching its own parameter.

    3. ...

    PHP fprintf() Return Value

    The PHP fprintf() function returns the length of the string written.

    PHP fprintf() Working Examples

    1. fprintf(): zero-padded integers

    <?php
    if (!($fp = fopen('date.txt', 'w'))) {
        return;
    }
    fprintf($fp, "%04d-%02d-%02d", $year, $month, $day);
    // will write the formatted ISO date to date.txt
    ?>

    2. fprintf(): formatting currency

    <?php
    if (!($fp = fopen('currency.txt', 'w'))) {
        return;
    }
    $money1 = 68.75;
    $money2 = 54.35;
    $money = $money1 + $money2;
    // echo $money will output "123.1";
    $len = fprintf($fp, '%01.2f', $money);
    // will write "123.10" to currency.txt
    echo "wrote $len bytes to currency.txt";
    // use the return value of fprintf to determine how many bytes we wrote
    ?>

    Important Points about PHP fprintf() Function

    1. The c type specifier ignores padding and width

    2. Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

    PHP get_html_translation_table() Function

    What does get_html_translation_table() do?

    The PHP get_html_translation_table() function will give you the translation table used by htmlspecialchars() and htmlentities().

    PHP get_html_translation_table() Syntax

     get_html_translation_table ([ int $table = HTML_SPECIALCHARS [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = "UTF-8" ]]] ) : array

    PHP get_html_translation_table() Parameters

    1. table — Which table to return. Either HTML_ENTITIES or HTML_SPECIALCHARS.

    2. flags — A bitmask of one or more of the following flags, which specify which quotes the table will contain as well as which document type the table is for. The default is ENT_COMPAT | ENT_HTML401.

    3. encoding — Encoding to use. If omitted, the default value for this argument is ISO-8859-1 in versions of PHP prior to 5.4.0, and UTF-8 from PHP 5.4.0 onwards.

    PHP get_html_translation_table() Return Value

    The PHP get_html_translation_table() function returns the translation table as an array, with the original characters as keys and entities as values.

    PHP get_html_translation_table() Working Examples

    1. Translation Table Example

    <?php
    var_dump(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES | ENT_HTML5));
    ?>

    Output of the above code:

    array(1510) {
     ["
    "]=>
     string(9) "&NewLine;"
     ["!"]=>
     string(6) "&excl;"
     ["""]=>
     string(6) "&quot;"
     ["#"]=>
     string(5) "&num;"
     ["$"]=>
     string(8) "&dollar;"
     ["%"]=>
     string(8) "&percnt;"
     ["&"]=>
     string(5) "&amp;"
     ["'"]=>
     string(6) "&apos;"
     // ...
    }

    Changelog for PHP get_html_translation_table() Function

    5.4.0 — The default value for the encoding parameter was changed to UTF-8.

    5.4.0 — The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.

    5.3.4 — The encoding parameter was added.

    Important Points about PHP get_html_translation_table() Function

    1. Special characters can be encoded in several ways. E.g. can be encoded as &quot;, &#34; or &#x22. get_html_translation_table() returns only the form used by htmlspecialchars() and htmlentities().

    Additional Tips from Fellow Developers

    Contributed By: kevin

    Be careful using get_html_translation_table() in a loop, as it's very slow.

    Contributed By: michael dot genesis

    The fact that MS-word and some other sources use CP-1252, and that it is so close to Latin1 ('ISO-8859-1') causes a lot of confusion. What confused me the most was finding that mySQL uses CP-1252 by default. 
     
    You may run into trouble if you find yourself tempted to do something like this: 
    <?php 
        $trans[chr(149)] = '&bull;';    // Bullet 
        $trans[chr(150)] = '&ndash;';    // En Dash 
        $trans[chr(151)] = '&mdash;';    // Em Dash 
        $trans[chr(152)] = '&tilde;';    // Small Tilde 
        $trans[chr(153)] = '&trade;';    // Trade Mark Sign 
    ?> 
     
    Don't do it. DON'T DO IT! 
     
    You can use: 
    <?php 
        $translationTable = get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES, 'WINDOWS-1252'); 
    ?> 
     
    or just convert directly: 
    <?php 
        $output = htmlentities($input, ENT_NOQUOTES, 'WINDOWS-1252'); 
    ?> 
     
    But your web page is probably encoded UTF-8, and you probably don't really want CP-1252 text flying around, so fix the character encoding first: 
    <?php 
        $output = mb_convert_encoding($input, 'UTF-8', 'WINDOWS-1252'); 
        $ouput = htmlentities($output); 
    ?>

    PHP hebrev() Function

    What does hebrev() do?

    The PHP hebrev() function will convert logical Hebrew text to visual text.

    PHP hebrev() Syntax

     hebrev ( string $hebrew_text [, int $max_chars_per_line = 0 ] ) : string

    PHP hebrev() Parameters

    1. hebrew_text — A Hebrew input string.

    2. max_chars_per_line — This optional parameter indicates maximum number of characters per line that will be returned.

    PHP hebrev() Return Value

    The PHP hebrev() function returns the visual string.

    PHP hebrevc() Function

    What does hebrevc() do?

    The PHP hebrevc() function will convert logical Hebrew text to visual text with newline conversion.

    PHP hebrevc() Syntax

     hebrevc ( string $hebrew_text [, int $max_chars_per_line = 0 ] ) : string

    PHP hebrevc() Parameters

    1. hebrew_text — A Hebrew input string.

    2. max_chars_per_line — This optional parameter indicates maximum number of characters per line that will be returned.

    PHP hebrevc() Return Value

    The PHP hebrevc() function returns the visual string.

    PHP hex2bin() Function

    What does hex2bin() do?

    The PHP hex2bin() function will decodes a hexadecimally encoded binary string.

    PHP hex2bin() Syntax

     hex2bin ( string $data ) : string

    PHP hex2bin() Parameters

    1. data — Hexadecimal representation of data.

    PHP hex2bin() Return Value

    The PHP hex2bin() function returns the binary representation of the given data or FALSE on failure.

    PHP hex2bin() Working Examples

    1. hex2bin() example

    <?php
    $hex = hex2bin("6578616d706c65206865782064617461");
    var_dump($hex);
    ?>

    Output of the above code:

    string(16) "example hex data"

    Changelog for PHP hex2bin() Function

    5.5.1 — A warning is thrown if the input string is invalid hexadecimal string.

    5.4.4 — A warning is thrown if the input string is of odd length. In PHP 5.4.0 the string was silently accepted, but the last byte was truncated.

    Important Points about PHP hex2bin() Function

    1. This function does NOT convert a hexadecimal number to a binary number. This can be done using the base_convert() function.

    Additional Tips from Fellow Developers

    Contributed By: Anonymous

    The function hex2bin does not exist in PHP5.
    You can use 'pack' instead :
    $binary_string = pack("H*" , $hex_string);

    PHP html_entity_decode() Function

    What does html_entity_decode() do?

    The PHP html_entity_decode() function will convert HTML entities to their corresponding characters.

    PHP html_entity_decode() Syntax

     html_entity_decode ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") ]] ) : string

    PHP html_entity_decode() Parameters

    1. string — The input string.

    2. flags — A bitmask of one or more of the following flags, which specify how to handle quotes and which document type to use. The default is ENT_COMPAT | ENT_HTML401.

    3. encoding — An optional argument defining the encoding used when converting characters.

    PHP html_entity_decode() Return Value

    The PHP html_entity_decode() function returns the decoded string.

    PHP html_entity_decode() Working Examples

    1. Decoding HTML entities

    <?php
    $orig = "I'll \"walk\" the <b>dog</b> now";
    $a = htmlentities($orig);
    $b = html_entity_decode($a);
    echo $a; // I'll &quot;walk&quot; the &lt;b&gt;dog&lt;/b&gt; now
    echo $b; // I'll "walk" the <b>dog</b> now
    ?>

    Changelog for PHP html_entity_decode() Function

    5.6.0 — The default value for the encoding parameter was changed to be the value of the default_charset configuration option.

    5.4.0 — Default encoding changed from ISO-8859-1 to UTF-8.

    5.4.0 — The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.

    Important Points about PHP html_entity_decode() Function

    1. You might wonder why trim(html_entity_decode(‘&nbsp;’)); doesn’t reduce the string to an empty string, that’s because the ‘&nbsp;’ entity is not ASCII code 32 (which is stripped by trim()) but ASCII code 160 (0xa0) in the default ISO 8859-1 encoding.

    Additional Tips from Fellow Developers

    Contributed By: Martin

    If you need something that converts &#[0-9]+ entities to UTF-8, this is simple and works: 
     
    <?php 
    /* Entity crap. / 
    $input = "Fovi&#269;"; 
     
    $output = preg_replace_callback("/(&#[0-9]+;)/", function($m) { return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); }, $input); 
     
    /* Plain UTF-8. */ 
    echo $output; 
    ?>

    Contributed By: txnull

    Use the following to decode all entities:
    <?php html_entity_decode($string, ENT_QUOTES | ENT_XML1, 'UTF-8') ?>
    I've checked these special entities: 
    - double quotes (&#34;)
    - single quotes (&#39; and &apos;) 
    - non printable chars (e.g. &#13;)
    With other $flags some or all won't be decoded.
    It seems that ENT_XML1 and ENT_XHTML are identical when decoding.

    PHP htmlentities() Function

    What does htmlentities() do?

    The PHP htmlentities() function will convert all applicable characters to HTML entities.

    PHP htmlentities() Syntax

     htmlentities ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool $double_encode = TRUE ]]] ) : string

    PHP htmlentities() Parameters

    1. string — The input string.

    2. flags — A bitmask of one or more of the following flags, which specify how to handle quotes, invalid code unit sequences and the used document type. The default is ENT_COMPAT | ENT_HTML401.

    3. encoding — An optional argument defining the encoding used when converting characters.

    4. double_encode — When double_encode is turned off PHP will not encode existing html entities. The default is to convert everything.

    PHP htmlentities() Return Value

    The PHP htmlentities() function returns the encoded string.

    PHP htmlentities() Working Examples

    1. A htmlentities() example

    <?php
    $str = "A 'quote' is <b>bold</b>";
    // Outputs: A 'quote' is &lt;b&gt;bold&lt;/b&gt;
    echo htmlentities($str);
    // Outputs: A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt;
    echo htmlentities($str, ENT_QUOTES);
    ?>

    2. Usage of ENT_IGNORE

    <?php
    $str = "\x8F!!!";
    // Outputs an empty string
    echo htmlentities($str, ENT_QUOTES, "UTF-8");
    // Outputs "!!!"
    echo htmlentities($str, ENT_QUOTES | ENT_IGNORE, "UTF-8");
    ?>

    Changelog for PHP htmlentities() Function

    5.6.0 — The default value for the encoding parameter was changed to be the value of the default_charset configuration option.

    5.4.0 — The default value for the encoding parameter was changed to UTF-8.

    5.4.0 — The constants ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.

    5.3.0 — The constant ENT_IGNORE was added.

    5.2.3 — The double_encode parameter was added.

    Additional Tips from Fellow Developers

    Contributed By: Sijmen Ruwhof

    An important note below about using this function to secure your application against Cross Site Scripting (XSS) vulnerabilities.
    When printing user input in an attribute of an HTML tag, the default configuration of htmlEntities() doesn't protect you against XSS, when using single quotes to define the border of the tag's attribute-value. XSS is then possible by injecting a single quote:
    <?php
    $_GET['a'] = "#000' onload='alert(document.cookie)";
    ?>
    XSS possible (insecure):
    <?php
    $href = htmlEntities($_GET['a']);
    print "<body bgcolor='$href'>"; # results in: <body bgcolor='#000' onload='alert(document.cookie)'>
    ?>
    Use the 'ENT_QUOTES' quote style option, to ensure no XSS is possible and your application is secure:
    <?php
    $href = htmlEntities($_GET['a'], ENT_QUOTES);
    print "<body bgcolor='$href'>"; # results in: <body bgcolor='#000&#039; onload=&#039;alert(document.cookie)'>
    ?>
    The 'ENT_QUOTES' option doesn't protect you against javascript evaluation in certain tag's attributes, like the 'href' attribute of the 'a' tag. When clicked on the link below, the given JavaScript will get executed:
    <?php
    $_GET['a'] = 'javascript:alert(document.cookie)';
    $href = htmlEntities($_GET['a'], ENT_QUOTES);
    print "<a href='$href'>link</a>"; # results in: <a href='javascript:alert(document.cookie)'>link</a>
    ?>

    Contributed By:

    I've seen lots of functions to convert all the entities, but I needed to do a fulltext search in a db field that had named entities instead of numeric entities (edited by tinymce), so I searched the tinymce source and found a string with the value->entity mapping. So, i wrote the following function to encode the user's query with named entities.
    The string I used is different of the original, because i didn't want to convert ' or ". The string is too long, so I had to cut it. To get the original check TinyMCE source and search for nbsp or other entity ;)
    <?php
    $entities_unmatched = explode(',', '160,nbsp,161,iexcl,162,cent, [...] ');
    $even = 1;
    foreach($entities_unmatched as $c) {
        if($even) {
            $ord = $c;
        } else {
            $entities_table[$ord] = $c;
        }
        $even = 1 - $even;
    }
    function encode_named_entities($str) {
        global $entities_table;
        
        $encoded_str = '';
        for($i = 0; $i < strlen($str); $i++) {
            $ent = @$entities_table[ord($str{$i})];
            if($ent) {
                $encoded_str .= "&$ent;";
            } else {
                $encoded_str .= $str{$i};
            }
        }
        return $encoded_str;
    }
    ?>

    Contributed By: n

    Html entities does not encode all unicode characters. It encodes what it can [all of latin1], and the others slip through. &#1033; is the nasty I use. I have searched for a function which encodes everything, but in the end I wrote this. This is as simple as I can get it. Consult an ansii table to custom include/omit chars you want/don't. I'm sure it's not that fast.
    // Unicode-proof htmlentities. 
    // Returns 'normal' chars as chars and weirdos as numeric html entites.
    function superentities( $str ){
        // get rid of existing entities else double-escape
        $str = html_entity_decode(stripslashes($str),ENT_QUOTES,'UTF-8'); 
        $ar = preg_split('/(?<!^)(?!$)/u', $str );  // return array of every multi-byte character
        foreach ($ar as $c){
            $o = ord($c);
            if ( (strlen($c) > 1) || /* multi-byte [unicode] */
                ($o <32 || $o > 126) || /* <- control / latin weirdos -> */
                ($o >33 && $o < 40) ||/* quotes + ambersand */
                ($o >59 && $o < 63) /* html */
            ) {
                // convert to numeric entity
                $c = mb_encode_numericentity($c,array (0x0, 0xffff, 0, 0xffff), 'UTF-8');
            }
            $str2 .= $c;
        }
        return $str2;
    }

    Contributed By: phil

    The following will make a string completely safe for XML:
    <?php
    function philsXMLClean($strin) {
            $strout = null;
            for ($i = 0; $i < strlen($strin); $i++) {
                    $ord = ord($strin[$i]);
                    if (($ord > 0 && $ord < 32) || ($ord >= 127)) {
                            $strout .= "&amp;#{$ord};";
                    }
                    else {
                            switch ($strin[$i]) {
                                    case '<':
                                            $strout .= '&lt;';
                                            break;
                                    case '>':
                                            $strout .= '&gt;';
                                            break;
                                    case '&':
                                            $strout .= '&amp;';
                                            break;
                                    case '"':
                                            $strout .= '&quot;';
                                            break;
                                    default:
                                            $strout .= $strin[$i];
                            }
                    }
            }
            return $strout;
    }
    ?>

    PHP htmlspecialchars() Function

    What does htmlspecialchars() do?

    The PHP htmlspecialchars() function will convert special characters to HTML entities.

    PHP htmlspecialchars() Syntax

     htmlspecialchars ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool $double_encode = TRUE ]]] ) : string

    PHP htmlspecialchars() Parameters

    1. string — The string being converted.

    2. flags — A bitmask of one or more of the following flags, which specify how to handle quotes, invalid code unit sequences and the used document type. The default is ENT_COMPAT | ENT_HTML401.

    3. encoding — An optional argument defining the encoding used when converting characters.

    4. double_encode — When double_encode is turned off PHP will not encode existing html entities, the default is to convert everything.

    PHP htmlspecialchars() Return Value

    The PHP htmlspecialchars() function returns the converted string.

    PHP htmlspecialchars() Working Examples

    1. htmlspecialchars() example

    <?php
    $new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
    echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
    ?>

    Changelog for PHP htmlspecialchars() Function

    5.6.0 — The default value for the encoding parameter was changed to be the value of the default_charset configuration option.

    5.4.0 — The default value for the encoding parameter was changed to UTF-8.

    5.4.0 — The constants ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.

    5.3.0 — The constant ENT_IGNORE was added.

    5.2.3 — The double_encode parameter was added.

    Important Points about PHP htmlspecialchars() Function

    1. Note that this function does not translate anything beyond what is listed above. For full entity translation, see htmlentities().

    2. In case of an ambiguous flags value, the following rules apply:

    Additional Tips from Fellow Developers

    Contributed By: Dave

    As of PHP 5.4 they changed default encoding from "ISO-8859-1" to "UTF-8". So if you get null from htmlspecialchars or htmlentities
    where you have only set 
    <?php
    echo htmlspecialchars($string);
    echo htmlentities($string);
    ?>
    you can fix it by
    <?php
    echo htmlspecialchars($string, ENT_COMPAT,'ISO-8859-1', true);
    echo htmlentities($string, ENT_COMPAT,'ISO-8859-1', true);
    ?> 
    On linux you can find the scripts you need to fix by
    grep -Rl "htmlspecialchars\\|htmlentities" /path/to/php/scripts/

    Contributed By: Mike Robinson

    Unfortunately, as far as I can tell, the PHP devs did not provide ANY way to set the default encoding used by htmlspecialchars() or htmlentities(), even though they changed the default encoding in PHP 5.4 (*golf clap for PHP devs*). To save someone the time of trying it, this does not work:
    <?php
    ini_set('default_charset', $charset); // doesn't work.
    ?>
    Unfortunately, the only way to not have to explicitly provide the second and third parameter every single time this function is called (which gets extremely tedious) is to write your own function as a wrapper:
    <?php
    define('CHARSET', 'ISO-8859-1');
    define('REPLACE_FLAGS', ENT_COMPAT | ENT_XHTML);
    function html($string) {
        return htmlspecialchars($string, REPLACE_FLAGS, CHARSET);
    }
    echo html("ñ"); // works
    ?>
    You can do the same for htmlentities()

    Contributed By: Thomasvdbulk

    I searched for a while for a script, that could see the difference between an html tag and just < and > placed in the text, 
    the reason is that i recieve text from a database,
    wich is inserted by an html form, and contains text and html tags, 
    the text can contain < and >, so does the tags,
    with htmlspecialchars you can validate your text to XHTML,
    but you'll also change the tags, like <b> to &lt;b&gt;,
    so i needed a script that could see the difference between those two...
    but i couldn't find one so i made my own one, 
    i havent fully tested it, but the parts i tested worked perfect!
    just for people that were searching for something like this,
    it may looks big, could be done easier, but it works for me, so im happy.
    <?php
    function fixtags($text){
    $text = htmlspecialchars($text);
    $text = preg_replace("/=/", "=\"\"", $text);
    $text = preg_replace("/&quot;/", "&quot;\"", $text);
    $tags = "/&lt;(\/|)(\w*)(\ |)(\w*)([\\\=]*)(?|(\")\"&quot;\"|)(?|(.*)?&quot;(\")|)([\ ]?)(\/|)&gt;/i";
    $replacement = "<$1$2$3$4$5$6$7$8$9$10>";
    $text = preg_replace($tags, $replacement, $text);
    $text = preg_replace("/=\"\"/", "=", $text);
    return $text;
    }
    ?>
    an example:
    <?php
    $string = "
    this is smaller < than this<br /> 
    this is greater > than this<br />
    this is the same = as this<br />
    <a href=\"http://www.example.com/example.php?test=test\">This is a link</a><br />
    <b>Bold</b> <i>italic</i> etc...";
    echo fixtags($string);
    ?>
    will echo:
    this is smaller &lt; than this<br /> 
    this is greater &gt; than this<br /> 
    this is the same = as this<br /> 
    <a href="http://www.example.com/example.php?test=test">This is a link</a><br /> 
    <b>Bold</b> <i>italic</i> etc...
    I hope its helpfull!!

    PHP htmlspecialchars_decode() Function

    What does htmlspecialchars_decode() do?

    The PHP htmlspecialchars_decode() function will convert special HTML entities back to characters .

    PHP htmlspecialchars_decode() Syntax

     htmlspecialchars_decode ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 ] ) : string

    PHP htmlspecialchars_decode() Parameters

    1. string — The string to decode.

    2. flags — A bitmask of one or more of the following flags, which specify how to handle quotes and which document type to use. The default is ENT_COMPAT | ENT_HTML401.

    PHP htmlspecialchars_decode() Return Value

    The PHP htmlspecialchars_decode() function returns the decoded string.

    PHP htmlspecialchars_decode() Working Examples

    1. A htmlspecialchars_decode() example

    <?php
    $str = "<p>this -&gt; &quot;</p>\n";
    echo htmlspecialchars_decode($str);
    // note that here the quotes aren't converted
    echo htmlspecialchars_decode($str, ENT_NOQUOTES);
    ?>

    Output of the above code:

    <p>this -> "</p>
    <p>this -> &quot;</p>

    Changelog for PHP htmlspecialchars_decode() Function

    5.4.0 — The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.

    PHP implode() Function

    What does implode() do?

    The PHP implode() function will join array elements with a glue string.

    PHP implode() Syntax

     implode ( string $glue , array $pieces ) : string
     implode ( array $pieces ) : string

    PHP implode() Parameters

    1. glue — Defaults to an empty string.

    2. pieces — The array of strings to implode.

    PHP implode() Return Value

    The PHP implode() function returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.

    PHP implode() Working Examples

    1. implode() example

    <?php
    $array = array('lastname', 'email', 'phone');
    $comma_separated = implode(",", $array);
    echo $comma_separated; // lastname,email,phone
    // Empty string when using an empty array:
    var_dump(implode('hello', array())); // string(0) ""
    ?>

    Important Points about PHP implode() Function

    1. implode() can, for historical reasons, accept its parameters in either order. For consistency with explode(), however, it may be less confusing to use the documented order of arguments.

    Additional Tips from Fellow Developers

    Contributed By: houston_roadrunner

    It should be noted that an array with one or no elements works fine. for example:
    <?php
        $a1 = array("1","2","3");
        $a2 = array("a");
        $a3 = array();
        
        echo "a1 is: '".implode("','",$a1)."'<br>";
        echo "a2 is: '".implode("','",$a2)."'<br>";
        echo "a3 is: '".implode("','",$a3)."'<br>";
    ?>
    will produce:
    ===========
    a1 is: '1','2','3'
    a2 is: 'a'
    a3 is: ''

    Contributed By: omar dot ajoue

    Can also be used for building tags or complex lists, like the following:
    <?php
    $elements = array('a', 'b', 'c');
    echo "<ul><li>" . implode("</li><li>", $elements) . "</li></ul>";
    ?>
    This is just an example, you can create a lot more just finding the right glue! ;)

    Contributed By: ASchmidt

    It's not obvious from the samples, if/how associative arrays are handled. The "implode" function acts on the array "values", disregarding any keys:
    <?php
    declare(strict_types=1);
    $a = array( 'one','two','three' );
    $b = array( '1st' => 'four', 'five', '3rd' => 'six' );
    echo implode( ',', $a ),'/', implode( ',', $b );
    ?>
    outputs:
    one,two,three/four,five,six

    Contributed By: Felix Rauch

    It might be worthwhile noting that the array supplied to implode() can contain objects, provided the objects implement the __toString() method.
    Example:
    <?php
    class Foo
    {
        protected $title;
        public function __construct($title)
        {
            $this->title = $title;
        }
        public function __toString()
        {
            return $this->title;
        }
    }
    $array = [
        new Foo('foo'),
        new Foo('bar'),
        new Foo('qux')
    ];
    echo implode('; ', $array);
    ?>
    will output:
    foo; bar; qux

    Contributed By: php.net

    Also quite handy in INSERT statements:
    <?php
       // array containing data
       $array = array(
          "name" => "John",
          "surname" => "Doe",
          "email" => "j.doe@intelligence.gov"
       );
       // build query...
       $sql  = "INSERT INTO table";
       // implode keys of $array...
       $sql .= " (`".implode("`, `", array_keys($array))."`)";
       // implode values of $array...
       $sql .= " VALUES ('".implode("', '", $array)."') ";
       // execute query...
       $result = mysql_query($sql) or die(mysql_error());
    ?>

    Contributed By: alexey dot klimko

    If you want to implode an array of booleans, you will get a strange result:
    <?php
    var_dump(implode('',array(true, true, false, false, true)));
    ?>
    Output:
    string(3) "111"
    TRUE became "1", FALSE became nothing.

    Contributed By: Anonymous

    It may be worth noting that if you accidentally call implode on a string rather than an array, you do NOT get your string back, you get NULL:
    <?php
    var_dump(implode(':', 'xxxxx'));
    ?>
    returns
    NULL
    This threw me for a little while.

    Contributed By: masterandujar

    Even handier if you use the following: 
     
    <?php 
    $id_nums = array(1,6,12,18,24); 
     
    $id_nums = implode(", ", $id_nums); 
                    
    $sqlquery = "Select name,email,phone from usertable where user_id IN ($id_nums)"; 
     
    // $sqlquery becomes "Select name,email,phone from usertable where user_id IN (1,6,12,18,24)" 
    ?> 
     
    Be sure to escape/sanitize/use prepared statements if you get the ids from users.

    PHP join() Function

    What does join() do?

    The PHP join() function will this function is an alias of: implode().

    PHP join() Syntax

    PHP join() Parameters

      This function does not accept any parameters.

      PHP lcfirst() Function

      What does lcfirst() do?

      The PHP lcfirst() function will make a string’s first character lowercase.

      PHP lcfirst() Syntax

       lcfirst ( string $str ) : string

      PHP lcfirst() Parameters

      1. str — The input string.

      PHP lcfirst() Return Value

      The PHP lcfirst() function returns the resulting string.

      PHP lcfirst() Working Examples

      1. lcfirst() example

      <?php
      $foo = 'HelloWorld';
      $foo = lcfirst($foo);             // helloWorld
      $bar = 'HELLO WORLD!';
      $bar = lcfirst($bar);             // hELLO WORLD!
      $bar = lcfirst(strtoupper($bar)); // hELLO WORLD!
      ?>

      Additional Tips from Fellow Developers

      Contributed By: phpnet

      Easiest work-around I've found for <5.3:
      <?php
      $string = "CamelCase"
      $string{0} = strtolower($string{0})
      echo $string; // outputs camelCase
      ?>

      PHP levenshtein() Function

      What does levenshtein() do?

      The PHP levenshtein() function will calculate Levenshtein distance between two strings.

      PHP levenshtein() Syntax

       levenshtein ( string $str1 , string $str2 ) : int
       levenshtein ( string $str1 , string $str2 , int $cost_ins , int $cost_rep , int $cost_del ) : int

      PHP levenshtein() Parameters

      1. str1 — One of the strings being evaluated for Levenshtein distance.

      2. str2 — One of the strings being evaluated for Levenshtein distance.

      3. cost_ins — Defines the cost of insertion.

      4. cost_rep — Defines the cost of replacement.

      5. cost_del — Defines the cost of deletion.

      PHP levenshtein() Return Value

      The PHP levenshtein() function returns the Levenshtein-Distance between the two argument strings or -1, if one of the argument strings is longer than the limit of 255 characters.

      PHP levenshtein() Working Examples

      1. levenshtein() example

      <?php
      // input misspelled word
      $input = 'carrrot';
      // array of words to check against
      $words  = array('apple','pineapple','banana','orange',
                      'radish','carrot','pea','bean','potato');
      // no shortest distance found, yet
      $shortest = -1;
      // loop through words to find the closest
      foreach ($words as $word) {
          // calculate the distance between the input word,
          // and the current word
          $lev = levenshtein($input, $word);
          // check for an exact match
          if ($lev == 0) {
              // closest word is this one (exact match)
              $closest = $word;
              $shortest = 0;
              // break out of the loop; we've found an exact match
              break;
          }
          // if this distance is less than the next found shortest
          // distance, OR if a next shortest word has not yet been found
          if ($lev <= $shortest || $shortest < 0) {
              // set the closest match, and shortest distance
              $closest  = $word;
              $shortest = $lev;
          }
      }
      echo "Input word: $input\n";
      if ($shortest == 0) {
          echo "Exact match found: $closest\n";
      } else {
          echo "Did you mean: $closest?\n";
      }
      ?>

      Output of the above code:

      Input word: carrrot
      Did you mean: carrot?

      Additional Tips from Fellow Developers

      Contributed By: luciole75w

      The levenshtein function processes each byte of the input string individually. Then for multibyte encodings, such as UTF-8, it may give misleading results.
      Example with a french accented word :
      - levenshtein('notre', 'votre') = 1
      - levenshtein('notre', 'nôtre') = 2 (huh ?!)
      You can easily find a multibyte compliant PHP implementation of the levenshtein function but it will be of course much slower than the C implementation.
      Another option is to convert the strings to a single-byte (lossless) encoding so that they can feed the fast core levenshtein function.
      Here is the conversion function I used with a search engine storing UTF-8 strings, and a quick benchmark. I hope it will help.
      <?php
      // Convert an UTF-8 encoded string to a single-byte string suitable for
      // functions such as levenshtein.
      // 
      // The function simply uses (and updates) a tailored dynamic encoding
      // (in/out map parameter) where non-ascii characters are remapped to
      // the range [128-255] in order of appearance.
      //
      // Thus it supports up to 128 different multibyte code points max over
      // the whole set of strings sharing this encoding.
      //
      function utf8_to_extended_ascii($str, &$map)
      {
          // find all multibyte characters (cf. utf-8 encoding specs)
          $matches = array();
          if (!preg_match_all('/[\xC0-\xF7][\x80-\xBF]+/', $str, $matches))
              return $str; // plain ascii string
          
          // update the encoding map with the characters not already met
          foreach ($matches[0] as $mbc)
              if (!isset($map[$mbc]))
                  $map[$mbc] = chr(128 + count($map));
          
          // finally remap non-ascii characters
          return strtr($str, $map);
      }
      // Didactic example showing the usage of the previous conversion function but,
      // for better performance, in a real application with a single input string
      // matched against many strings from a database, you will probably want to
      // pre-encode the input only once.
      //
      function levenshtein_utf8($s1, $s2)
      {
          $charMap = array();
          $s1 = utf8_to_extended_ascii($s1, $charMap);
          $s2 = utf8_to_extended_ascii($s2, $charMap);
          
          return levenshtein($s1, $s2);
      }
      ?>
      Results (for about 6000 calls)
      - reference time core C function (single-byte) : 30 ms
      - utf8 to ext-ascii conversion + core function : 90 ms
      - full php implementation : 3000 ms

      Contributed By: paulrowe

      [EDITOR'S NOTE: original post and 2 corrections combined into 1 -- mgf] 
       
      Here is an implementation of the Levenshtein Distance calculation that only uses a one-dimensional array and doesn't have a limit to the string length. This implementation was inspired by maze generation algorithms that also use only one-dimensional arrays. 
       
      I have tested this function with two 532-character strings and it completed in 0.6-0.8 seconds. 
       
      <?php 
      /* 
      * This function starts out with several checks in an attempt to save time. 
      *   1.  The shorter string is always used as the "right-hand" string (as the size of the array is based on its length).  
      *   2.  If the left string is empty, the length of the right is returned. 
      *   3.  If the right string is empty, the length of the left is returned. 
      *   4.  If the strings are equal, a zero-distance is returned. 
      *   5.  If the left string is contained within the right string, the difference in length is returned. 
      *   6.  If the right string is contained within the left string, the difference in length is returned. 
      * If none of the above conditions were met, the Levenshtein algorithm is used. 
      */ 
      function LevenshteinDistance($s1, $s2) 
      { 
        $sLeft = (strlen($s1) > strlen($s2)) ? $s1 : $s2; 
        $sRight = (strlen($s1) > strlen($s2)) ? $s2 : $s1; 
        $nLeftLength = strlen($sLeft); 
        $nRightLength = strlen($sRight); 
        if ($nLeftLength == 0) 
          return $nRightLength; 
        else if ($nRightLength == 0) 
          return $nLeftLength; 
        else if ($sLeft === $sRight) 
          return 0; 
        else if (($nLeftLength < $nRightLength) && (strpos($sRight, $sLeft) !== FALSE)) 
          return $nRightLength - $nLeftLength; 
        else if (($nRightLength < $nLeftLength) && (strpos($sLeft, $sRight) !== FALSE)) 
          return $nLeftLength - $nRightLength; 
        else { 
          $nsDistance = range(1, $nRightLength + 1); 
          for ($nLeftPos = 1; $nLeftPos <= $nLeftLength; ++$nLeftPos) 
          { 
            $cLeft = $sLeft[$nLeftPos - 1]; 
            $nDiagonal = $nLeftPos - 1; 
            $nsDistance[0] = $nLeftPos; 
            for ($nRightPos = 1; $nRightPos <= $nRightLength; ++$nRightPos) 
            { 
              $cRight = $sRight[$nRightPos - 1]; 
              $nCost = ($cRight == $cLeft) ? 0 : 1; 
              $nNewDiagonal = $nsDistance[$nRightPos]; 
              $nsDistance[$nRightPos] = 
                min($nsDistance[$nRightPos] + 1, 
                    $nsDistance[$nRightPos - 1] + 1, 
                    $nDiagonal + $nCost); 
              $nDiagonal = $nNewDiagonal; 
            } 
          } 
          return $nsDistance[$nRightLength]; 
        } 
      } 
      ?>

      PHP localeconv() Function

      What does localeconv() do?

      The PHP localeconv() function will give you an associative array containing localized numeric and monetary formatting information.

      PHP localeconv() Syntax

       localeconv ( void ) : array

      PHP localeconv() Parameters

        This function does not accept any parameters.

        PHP localeconv() Return Value

        The PHP localeconv() function returns data based upon the current locale as set by setlocale(). The associative array that is returned contains the following fields:

        PHP localeconv() Working Examples

        1. localeconv() example

        <?php
        if (false !== setlocale(LC_ALL, 'nl_NL.UTF-8@euro')) {
            $locale_info = localeconv();
            print_r($locale_info);
        }
        ?>

        Output of the above code:

        Array
        (
         [decimal_point] => .
         [thousands_sep] =>
         [int_curr_symbol] => EUR
         [currency_symbol] => €
         [mon_decimal_point] => ,
         [mon_thousands_sep] =>
         [positive_sign] =>
         [negative_sign] => -
         [int_frac_digits] => 2
         [frac_digits] => 2
         [p_cs_precedes] => 1
         [p_sep_by_space] => 1
         [n_cs_precedes] => 1
         [n_sep_by_space] => 1
         [p_sign_posn] => 1
         [n_sign_posn] => 2
         [grouping] => Array
         (
         )
         [mon_grouping] => Array
         (
         [0] => 3
         [1] => 3
         )
        )

        PHP ltrim() Function

        What does ltrim() do?

        The PHP ltrim() function will strip whitespace (or other characters) from the beginning of a string.

        PHP ltrim() Syntax

         ltrim ( string $str [, string $character_mask ] ) : string

        PHP ltrim() Parameters

        1. str — The input string.

        2. character_mask — You can also specify the characters you want to strip, by means of the character_mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

        PHP ltrim() Return Value

        The PHP ltrim() function returns a string with whitespace stripped from the beginning of str. Without the second parameter, ltrim() will strip these characters:

        PHP ltrim() Working Examples

        1. Usage example of ltrim()

        <?php
        $text = "\t\tThese are a few words :) ...  ";
        $binary = "\x09Example string\x0A";
        $hello  = "Hello World";
        var_dump($text, $binary, $hello);
        print "\n";
        $trimmed = ltrim($text);
        var_dump($trimmed);
        $trimmed = ltrim($text, " \t.");
        var_dump($trimmed);
        $trimmed = ltrim($hello, "Hdle");
        var_dump($trimmed);
        // trim the ASCII control characters at the beginning of $binary
        // (from 0 to 31 inclusive)
        $clean = ltrim($binary, "\x00..\x1F");
        var_dump($clean);
        ?>

        Output of the above code:

        string(32) " These are a few words :) ... "
        string(16) " Example string
        "
        string(11) "Hello World"
        string(30) "These are a few words :) ... "
        string(30) "These are a few words :) ... "
        string(7) "o World"
        string(15) "Example string
        "

        Additional Tips from Fellow Developers

        Contributed By: tavi undersc 10 from yahoocom

        When using a $character_mask the trimming stops at the first character that is not on that mask.
        So in the $string = "Hello world" example with $character_mask = "Hdle", ltrim($hello, $character_mask) goes like this:
        1. Check H from "Hello world" => it is in the $character_mask, so remove it
        2. Check e from "ello world" => it is in the $character_mask, so remove it
        3. Check l from "llo world" => it is in the $character_mask, so remove it
        4. Check l from "lo world" => it is in the $character_mask, so remove it
        5. Check o from "o world" => it is NOT in the $character_mask, exit the function
        Remaining string is "o world".
        I hope it helps someone as I had a confusing moment with this function.

        PHP md5() Function

        What does md5() do?

        The PHP md5() function will give you that hash.

        PHP md5() Syntax

         md5 ( string $str [, bool $raw_output = FALSE ] ) : string

        PHP md5() Parameters

        1. str — The string.

        2. raw_output — If the optional raw_output is set to TRUE, then the md5 digest is instead returned in raw binary format with a length of 16.

        PHP md5() Return Value

        The PHP md5() function returns the hash as a 32-character hexadecimal number.

        PHP md5() Working Examples

        1. A md5() example

        <?php
        $str = 'apple';
        if (md5($str) === '1f3870be274f6c49b3e31a0c6728957f') {
            echo "Would you like a green or red apple?";
        }
        ?>

        Important Points about PHP md5() Function

        1. It is not recommended to use this function to secure passwords, due to the fast nature of this hashing algorithm. See the Password Hashing FAQ for details and best practices.

        Additional Tips from Fellow Developers

        Contributed By: Ray.Paseur sometimes uses Gmail

        Md5('240610708') == md5('QNKCDZO')
        This comparison is true because both md5() hashes start '0e' so PHP type juggling understands these strings to be scientific notation.  By definition, zero raised to any power is zero.

        PHP md5_file() Function

        What does md5_file() do?

        The PHP md5_file() function will give you that hash. The hash is a 32-character hexadecimal number.

        PHP md5_file() Syntax

         md5_file ( string $filename [, bool $raw_output = FALSE ] ) : string

        PHP md5_file() Parameters

        1. filename — The filename

        2. raw_output — When TRUE, returns the digest in raw binary format with a length of 16.

        PHP md5_file() Return Value

        The PHP md5_file() function returns a string on success, FALSE otherwise.

        PHP md5_file() Working Examples

        1. Usage example of md5_file()

        <?php
        $file = 'php-5.3.0alpha2-Win32-VC9-x64.zip';
        echo 'MD5 file hash of ' . $file . ': ' . md5_file($file);
        ?>

        Changelog for PHP md5_file() Function

        5.1.0 — Changed the function to use the streams API. It means that you can use it with wrappers, like md5_file(‘http://example.com/..’)

        Additional Tips from Fellow Developers

        Contributed By: Chris

        If you just need to find out if two files are identical, comparing file hashes can be inefficient, especially on large files.  There's no reason to read two whole files and do all the math if the second byte of each file is different.  If you don't need to store the hash value for later use, there may not be a need to calculate the hash value just to compare files.  This can be much faster:
        <?php
        define('READ_LEN', 4096);
        if(files_identical('file1.txt', 'file2.txt'))
            echo 'files identical';
        else
            echo 'files not identical';
        //   pass two file names
        //   returns TRUE if files are the same, FALSE otherwise
        function files_identical($fn1, $fn2) {
            if(filetype($fn1) !== filetype($fn2))
                return FALSE;
            if(filesize($fn1) !== filesize($fn2))
                return FALSE;
            if(!$fp1 = fopen($fn1, 'rb'))
                return FALSE;
            if(!$fp2 = fopen($fn2, 'rb')) {
                fclose($fp1);
                return FALSE;
            }
            $same = TRUE;
            while (!feof($fp1) and !feof($fp2))
                if(fread($fp1, READ_LEN) !== fread($fp2, READ_LEN)) {
                    $same = FALSE;
                    break;
                }
            if(feof($fp1) !== feof($fp2))
                $same = FALSE;
            fclose($fp1);
            fclose($fp2);
            return $same;
        }
        ?>

        Contributed By: lukasamd

        It's faster to use md5sum than openssl md5:
        <?php
        $begin = microtime(true);
        $file_path = '../backup_file1.tar.gz';
        $result = explode("  ", exec("md5sum $file_path"));
        echo "Hash = ".$result[0]."<br />";
        # Here 7 other big files (20-300 MB)
        $end = microtime(true) - $begin;
        echo "Time = $end";
        # Time = 4.4475841522217 
        #Method with openssl
        # Time = 12.1463856900543
        ?>
        About 3x faster

        PHP metaphone() Function

        What does metaphone() do?

        The PHP metaphone() function will calculates the metaphone key of str.

        PHP metaphone() Syntax

         metaphone ( string $str [, int $phonemes = 0 ] ) : string

        PHP metaphone() Parameters

        1. str — The input string.

        2. phonemes — This parameter restricts the returned metaphone key to phonemes characters in length. The default value of 0 means no restriction.

        PHP metaphone() Return Value

        The PHP metaphone() function returns the metaphone key as a string, or FALSE on failure.

        PHP metaphone() Working Examples

        1. metaphone() basic example

        <?php
        var_dump(metaphone('programming'));
        var_dump(metaphone('programmer'));
        ?>

        Output of the above code:

        string(7) "PRKRMNK"
        string(6) "PRKRMR"

        2. Using the phonemes parameter

        <?php
        var_dump(metaphone('programming', 5));
        var_dump(metaphone('programmer', 5));
        ?>

        Output of the above code:

        string(5) "PRKRM"
        string(5) "PRKRM"

        Additional Tips from Fellow Developers

        Contributed By: mail

        You can use the metaphone function quite effectively with phrases by taking the levenshtein distances between two metaphone codes, and then taking this as a percentage of the length of the original metaphone code. thus you can define a percentage error, (say 20%) and accept only matches that are closer than that. i've found this works quite effectively in a function i am using on my website where an album name that the user entered is verified against existing album names that may be similar. this is also an excellent way of people being able to vaguely remember a phrase and get several suggestions out of the database. so you could type "i stiched nine times" with an error percentage of, say, 50 and still get 'a stitch in time saves nine' back as a match.

        Contributed By: php

        A double metaphone pecl module is available: http://pecl.php.net/package/doublemetaphone

        Contributed By: Vipindas K.S

        Metaphone
        =======================
        The metaphone() function can be used for spelling applications.This function returns the metaphone key of the string on success, or FALSE on failure.Its main use is when you are searching a genealogy database. check to see if a metaphone search is offered. It is also useful in making/searching family tree.
        Given below is a simple code that calculates and compares two strings to find whether its metaphone codes are equivalent.
        html code
        ==========
        <html>
        <body>
        <form action="test.php" name="test" method="get">
        Name1:<input type="text" name="name1" /><br />
        Name2:<input type="text" name="name2" /><br />
        <input type="submit" name="submit" value="compare" />
        </form>
        <!--php code begins here -->
        <?php
        if(isset($_GET['submit']))
        {
        $str1 = $_GET['name1'];
        $str2 = $_GET['name2'];
        $meta_one=metaphone($str1);
        $meta_two=metaphone($str2);
        echo "metaphone code for ".$str1." is ". $meta_one;
        echo "<br />";
        echo "metaphone code for ".$str2." is ". $meta_two."<br>";
        if($meta_one==$meta_two)
        {
        echo "metaphone codes are matching";
        }
        else
        {
        echo "metaphone codes are not matching";
        }
        }
        ?>
        </body>
        </html>
        Metaphone  algorithm was developed by Lawrence Philips.
        Lawrence Philips' RULES follow:
         The 16 consonant sounds:
                                                     |--- ZERO represents "th"
                                                     |
              B  X  S  K  J  T  F  H  L  M  N  P  R  0  W  Y
         Exceptions:
           Beginning of word: "ae-", "gn", "kn-", "pn-", "wr-"  ----> drop first letter
                              "Aebersold", "Gnagy", "Knuth", "Pniewski", "Wright"
           Beginning of word: "x"                                ----> change to "s"
                                              as in "Deng Xiaopeng"
           Beginning of word: "wh-"                              ----> change to "w"
                                              as in "Whalen"
         Transformations:
           B ----> B      unless at the end of word after "m", as in "dumb", "McComb"
           C ----> X      (sh) if "-cia-" or "-ch-"
                   S      if "-ci-", "-ce-", or "-cy-"
                          SILENT if "-sci-", "-sce-", or "-scy-"
                   K      otherwise, including in "-sch-"
           D ----> J      if in "-dge-", "-dgy-", or "-dgi-"
                   T      otherwise
           F ----> F
           G ---->        SILENT if in "-gh-" and not at end or before a vowel
                                    in "-gn" or "-gned"
                                    in "-dge-" etc., as in above rule
                   J      if before "i", or "e", or "y" if not double "gg"
                   K      otherwise
           H ---->        SILENT if after vowel and no vowel follows
                                 or after "-ch-", "-sh-", "-ph-", "-th-", "-gh-"
                   H      otherwise
           J ----> J
           K ---->        SILENT if after "c"
                   K      otherwise
           L ----> L
           M ----> M
           N ----> N
           P ----> F      if before "h"
                   P      otherwise
           Q ----> K
           R ----> R
           S ----> X      (sh) if before "h" or in "-sio-" or "-sia-"
                   S      otherwise
           T ----> X      (sh) if "-tia-" or "-tio-"
                   0      (th) if before "h"
                          silent if in "-tch-"
                   T      otherwise
           V ----> F
           W ---->        SILENT if not followed by a vowel
                   W      if followed by a vowel
           X ----> KS
           Y ---->        SILENT if not followed by a vowel
                   Y      if followed by a vowel
           Z ----> S

        PHP money_format() Function

        What does money_format() do?

        The PHP money_format() function will give you a formatted version of number. This function wraps the C library function strfmon(), with the difference that this implementation converts only one number at a time.

        PHP money_format() Syntax

         money_format ( string $format , float $number ) : string

        PHP money_format() Parameters

        1. format — The format specification consists of the following sequence:

        2. =f — The character = followed by a (single byte) character f to be used as the numeric fill character. The default fill character is space.

        3. ^ — Disable the use of grouping characters (as defined by the current locale).

        4. + or ( — Specify the formatting style for positive and negative numbers. If + is used, the locale’s equivalent for + and – will be used. If ( is used, negative amounts are enclosed in parenthesis. If no specification is given, the default is +.

        5. ! — Suppress the currency symbol from the output string.

        6. - — If present, it will make all fields left-justified (padded to the right), as opposed to the default which is for the fields to be right-justified (padded to the left).

        7. w — A decimal digit string specifying a minimum field width. Field will be right-justified unless the flag – is used. Default value is 0 (zero).

        8. #n — The maximum number of digits (n) expected to the left of the decimal character (e.g. the decimal point). It is used usually to keep formatted output aligned in the same columns, using the fill character if the number of digits is less than n. If the number of actual digits is bigger than n, then this specification is ignored.

        9. .p — A period followed by the number of digits (p) after the decimal character. If the value of p is 0 (zero), the decimal character and the digits to its right will be omitted. If no right precision is included, the default will dictated by the current local in use. The amount being formatted is rounded to the specified number of digits prior to formatting.

        10. i — The number is formatted according to the locale’s international currency format (e.g. for the USA locale: USD 1,234.56).

        11. n — The number is formatted according to the locale’s national currency format (e.g. for the de_DE locale: EU1.234,56).

        12. % — Returns the % character.

        13. number — The number to be formatted.

        PHP money_format() Return Value

        The PHP money_format() function returns the formatted string. Characters before and after the formatting string will be returned unchanged. Non-numeric number causes returning NULL and emitting E_WARNING.

        PHP money_format() Working Examples

        1. money_format() Example

        <?php
        $number = 1234.56;
        // let's print the international format for the en_US locale
        setlocale(LC_MONETARY, 'en_US');
        echo money_format('%i', $number) . "\n";
        // USD 1,234.56
        // Italian national format with 2 decimals`
        setlocale(LC_MONETARY, 'it_IT');
        echo money_format('%.2n', $number) . "\n";
        // Eu 1.234,56
        // Using a negative number
        $number = -1234.5672;
        // US national format, using () for negative numbers
        // and 10 digits for left precision
        setlocale(LC_MONETARY, 'en_US');
        echo money_format('%(#10n', $number) . "\n";
        // ($        1,234.57)
        // Similar format as above, adding the use of 2 digits of right
        // precision and '*' as a fill character
        echo money_format('%=*(#10.2n', $number) . "\n";
        // ($********1,234.57)
        // Let's justify to the left, with 14 positions of width, 8 digits of
        // left precision, 2 of right precision, without the grouping character
        // and using the international format for the de_DE locale.
        setlocale(LC_MONETARY, 'de_DE');
        echo money_format('%=*^-14#8.2i', 1234.56) . "\n";
        // Eu 1234,56****
        // Let's add some blurb before and after the conversion specification
        setlocale(LC_MONETARY, 'en_GB');
        $fmt = 'The final value is %i (after a 10%% discount)';
        echo money_format($fmt, 1234.56) . "\n";
        // The final value is  GBP 1,234.56 (after a 10% discount)
        ?>

        Important Points about PHP money_format() Function

        1. The function money_format() is only defined if the system has strfmon capabilities. For example, Windows does not, so money_format() is undefined in Windows.

        2. The LC_MONETARY category of the locale settings, affects the behavior of this function. Use setlocale() to set to the appropriate default locale before using this function.

        Additional Tips from Fellow Developers

        Contributed By: tim

        For most of us in the US, we don't want to see a "USD" for our currency symbol, so '%i' doesn't cut it.  Here's what I used that worked to get what most  people expect to see for a number format.
        $number = 123.4
        setlocale(LC_MONETARY, 'en_US.UTF-8');
        money_format('%.2n', $number);
        output:
        $123.40
        That gives me a dollar sign at the beginning, and 2 digits at the end.

        Contributed By: Rafael M. Salvioni

        This is a some function posted before, however various bugs were corrected. 
         
        Thank you to Stuart Roe by reporting the bug on printing signals. 
         
        <?php 
        /* 
        That it is an implementation of the function money_format for the 
        platforms that do not it bear.  
         
        The function accepts to same string of format accepts for the 
        original function of the PHP.  
         
        (Sorry. my writing in English is very bad)  
         
        The function is tested using PHP 5.1.4 in Windows XP 
        and Apache WebServer. 
        */ 
        function money_format($format, $number) 
        { 
            $regex  = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?'. 
                      '(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/'; 
            if (setlocale(LC_MONETARY, 0) == 'C') { 
                setlocale(LC_MONETARY, ''); 
            } 
            $locale = localeconv(); 
            preg_match_all($regex, $format, $matches, PREG_SET_ORDER); 
            foreach ($matches as $fmatch) { 
                $value = floatval($number); 
                $flags = array( 
                    'fillchar'  => preg_match('/\=(.)/', $fmatch[1], $match) ? 
                                   $match[1] : ' ', 
                    'nogroup'   => preg_match('/\^/', $fmatch[1]) > 0, 
                    'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ? 
                                   $match[0] : '+', 
                    'nosimbol'  => preg_match('/\!/', $fmatch[1]) > 0, 
                    'isleft'    => preg_match('/\-/', $fmatch[1]) > 0 
                ); 
                $width      = trim($fmatch[2]) ? (int)$fmatch[2] : 0; 
                $left       = trim($fmatch[3]) ? (int)$fmatch[3] : 0; 
                $right      = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits']; 
                $conversion = $fmatch[5]; 
         
                $positive = true; 
                if ($value < 0) { 
                    $positive = false; 
                    $value  *= -1; 
                } 
                $letter = $positive ? 'p' : 'n'; 
         
                $prefix = $suffix = $cprefix = $csuffix = $signal = ''; 
         
                $signal = $positive ? $locale['positive_sign'] : $locale['negative_sign']; 
                switch (true) { 
                    case $locale["{$letter}_sign_posn"] == 1 && $flags['usesignal'] == '+': 
                        $prefix = $signal; 
                        break; 
                    case $locale["{$letter}_sign_posn"] == 2 && $flags['usesignal'] == '+': 
                        $suffix = $signal; 
                        break; 
                    case $locale["{$letter}_sign_posn"] == 3 && $flags['usesignal'] == '+': 
                        $cprefix = $signal; 
                        break; 
                    case $locale["{$letter}_sign_posn"] == 4 && $flags['usesignal'] == '+': 
                        $csuffix = $signal; 
                        break; 
                    case $flags['usesignal'] == '(': 
                    case $locale["{$letter}_sign_posn"] == 0: 
                        $prefix = '('; 
                        $suffix = ')'; 
                        break; 
                } 
                if (!$flags['nosimbol']) { 
                    $currency = $cprefix . 
                                ($conversion == 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']) . 
                                $csuffix; 
                } else { 
                    $currency = ''; 
                } 
                $space  = $locale["{$letter}_sep_by_space"] ? ' ' : ''; 
         
                $value = number_format($value, $right, $locale['mon_decimal_point'], 
                         $flags['nogroup'] ? '' : $locale['mon_thousands_sep']); 
                $value = @explode($locale['mon_decimal_point'], $value); 
         
                $n = strlen($prefix) + strlen($currency) + strlen($value[0]); 
                if ($left > 0 && $left > $n) { 
                    $value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0]; 
                } 
                $value = implode($locale['mon_decimal_point'], $value); 
                if ($locale["{$letter}_cs_precedes"]) { 
                    $value = $prefix . $currency . $space . $value . $suffix; 
                } else { 
                    $value = $prefix . $value . $space . $currency . $suffix; 
                } 
                if ($width > 0) { 
                    $value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ? 
                             STR_PAD_RIGHT : STR_PAD_LEFT); 
                } 
         
                $format = str_replace($fmatch[0], $value, $format); 
            } 
            return $format; 
        } 
         
        ?>

        Contributed By: todoventas

        In Rafael M. Salvioni function localeconv(); returns an invalid array in my Windows XP SP3 running PHP 5.4.13 so to prevent the Warning Message: implode(): Invalid arguments passed i just add the $locale manually. For other languages just fill the array with the correct settings.
        <?
               $locale = array(
                'decimal_point'        => '.',
                'thousands_sep'        => '',
                'int_curr_symbol'    => 'EUR',
                'currency_symbol'    => '€',
                'mon_decimal_point'    => ',',
                'mon_thousands_sep'    => '.',
                'positive_sign'        => '',
                'negative_sign'     => '-',
                'int_frac_digits'    => 2,
                'frac_digits'        => 2,
                'p_cs_precedes'        => 0,
                'p_sep_by_space'    => 1,
                'p_sign_posn'        => 1,
                'n_sign_posn'        => 1,
                'grouping'            => array(),
                'mon_grouping'        => array(0 => 3, 1 => 3)
                
            );
        ?>

        Contributed By: jeremy

        If money_format doesn't seem to be working properly, make sure you are defining a valid locale.  For example, on Debian, 'en_US' is not a valid locale - you need 'en_US.UTF-8' or 'en_US.ISO-8559-1'.
        This was frustrating me for a while.  Debian has a list of valid locales at /usr/share/i18n/SUPPORTED; find yours there if it's not working properly.

        PHP nl2br() Function

        What does nl2br() do?

        The PHP nl2br() function will inserts HTML line breaks before all newlines in a string.

        PHP nl2br() Syntax

         nl2br ( string $string [, bool $is_xhtml = TRUE ] ) : string

        PHP nl2br() Parameters

        1. string — The input string.

        2. is_xhtml — Whether to use XHTML compatible line breaks or not.

        PHP nl2br() Return Value

        The PHP nl2br() function returns the altered string.

        PHP nl2br() Working Examples

        1. Using nl2br()

        <?php
        echo nl2br("foo isn't\n bar");
        ?>

        Output of the above code:

        foo isn't<br />
         bar

        2. Generating valid HTML markup using the is_xhtml parameter

        <?php
        echo nl2br("Welcome\r\nThis is my HTML document", false);
        ?>

        Output of the above code:

        Welcome<br>
        This is my HTML document

        3. Various newline separators

        <?php
        $string = "This\r\nis\n\ra\nstring\r";
        echo nl2br($string);
        ?>

        Output of the above code:

        This<br />
        is<br />
        a<br />
        string<br />

        Changelog for PHP nl2br() Function

        5.3.0 — Added the optional is_xhtml parameter. Before this version ‘<br />’ was always inserted.

        Additional Tips from Fellow Developers

        Contributed By: CGameProgrammer

        It's important to remember that this function does NOT replace newlines with <br> tags. Rather, it inserts a <br> tag before each newline, but it still preserves the newlines themselves! This caused problems for me regarding a function I was writing -- I forgot the newlines were still being preserved. 
         
        If you don't want newlines, do: 
         
        <?php 
        $Result = str_replace( "\n", '<br />', $Text ); 
        ?>

        Contributed By: ngkongs

        To replace all linebreaks to <br /> 
        the best solution (IMO) is: 
         
        <?php 
        function nl2br2($string) { 
        $string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string); 
        return $string; 
        } 
        ?> 
         
        because each OS have different ASCII chars for linebreak: 
        windows = \r\n 
        unix = \n 
        mac = \r 
         
        works perfect for me

        Contributed By: N/A

        Here's a more simple one:
        <?php
        /**
         * Convert BR tags to nl
         *
         * @param string The string to convert
         * @return string The converted string
         */
        function br2nl($string)
        {
            return preg_replace('/\<br(\s*)?\/?\>/i', "\n", $string);
        }
        ?>
        Enjoy

        Contributed By: fquffio

        Starting from PHP 4.3.10 and PHP 5.0.2, this should be the most correct way to replace <br /> and <br> tags with newlines and carriage returns.
        <?php
        /**
         * Convert BR tags to newlines and carriage returns.
         *
         * @param string The string to convert
         * @return string The converted string
         */
        function br2nl ( $string )
        {
            return preg_replace('/\<br(\s*)?\/?\>/i', PHP_EOL, $string);
        }
        ?>
        (Please note this is a minor edit of this function: http://php.net/nl2br#86678 )
        You might also want to be "platform specific", and therefore this function might be of some help:
        <?php
        /**
         * Convert BR tags to newlines and carriage returns.
         *
         * @param string The string to convert
         * @param string The string to use as line separator
         * @return string The converted string
         */
        function br2nl ( $string, $separator = PHP_EOL )
        {
            $separator = in_array($separator, array("\n", "\r", "\r\n", "\n\r", chr(30), chr(155), PHP_EOL)) ? $separator : PHP_EOL;  // Checks if provided $separator is valid.
            return preg_replace('/\<br(\s*)?\/?\>/i', $separator, $string);
        }
        ?>

        PHP nl_langinfo() Function

        What does nl_langinfo() do?

        The PHP nl_langinfo() function will give you all of the elements, nl_langinfo() allows you to select any specific element.

        PHP nl_langinfo() Syntax

         nl_langinfo ( int $item ) : string

        PHP nl_langinfo() Parameters

        1. item — item may be an integer value of the element or the constant name of the element. The following is a list of constant names for item that may be used and their description. Some of these constants may not be defined or hold no value for certain locales.

        PHP nl_langinfo() Return Value

        The PHP nl_langinfo() function returns the element as a string, or FALSE if item is not valid.

        PHP number_format() Function

        What does number_format() do?

        The PHP number_format() function will this function accepts either one, two, or four parameters (not three):

        PHP number_format() Syntax

         number_format ( float $number [, int $decimals = 0 ] ) : string
         number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," ) : string

        PHP number_format() Parameters

        1. number — The number being formatted.

        2. decimals — Sets the number of decimal points.

        3. dec_point — Sets the separator for the decimal point.

        4. thousands_sep — Sets the thousands separator.

        PHP number_format() Return Value

        The PHP number_format() function returns a formatted version of number.

        PHP number_format() Working Examples

        1. number_format() Example

        <?php
        $number = 1234.56;
        // english notation (default)
        $english_format_number = number_format($number);
        // 1,235
        // French notation
        $nombre_format_francais = number_format($number, 2, ',', ' ');
        // 1 234,56
        $number = 1234.5678;
        // english notation without thousands separator
        $english_format_number = number_format($number, 2, '.', '');
        // 1234.57
        ?>

        Changelog for PHP number_format() Function

        7.2.0 — number_format() was changed to not being able to return -0, previously -0 could be returned for cases like where number would be -0.01.

        5.4.0 — This function now supports multiple bytes in dec_point and thousands_sep. Only the first byte of each separator was used in older versions.

        Additional Tips from Fellow Developers

        Contributed By: thomas

        It's not explicitly documented; number_format also rounds:
        <?php
        $numbers = array(0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009);
        foreach ($numbers as $number)
            print $number."->".number_format($number, 2, '.', ',')."<br>";
        ?>
        0.001->0.00
        0.002->0.00
        0.003->0.00
        0.004->0.00
        0.005->0.01
        0.006->0.01
        0.007->0.01
        0.008->0.01
        0.009->0.01

        Contributed By: james

        Outputs a human readable number.
        <?php
            #    Output easy-to-read numbers
            #    by james at bandit.co.nz
            function bd_nice_number($n) {
                // first strip any formatting;
                $n = (0+str_replace(",","",$n));
                
                // is this a number?
                if(!is_numeric($n)) return false;
                
                // now filter it;
                if($n>1000000000000) return round(($n/1000000000000),1).' trillion';
                else if($n>1000000000) return round(($n/1000000000),1).' billion';
                else if($n>1000000) return round(($n/1000000),1).' million';
                else if($n>1000) return round(($n/1000),1).' thousand';
                
                return number_format($n);
            }
        ?>
        Outputs:
        247,704,360 -> 247.7 million
        866,965,260,000 -> 867 billion

        Contributed By: stm555

        I ran across an issue where I wanted to keep the entered precision of a real value, without arbitrarily rounding off what the user had submitted.
        I figured it out with a quick explode on the number before formatting. I could then format either side of the decimal.
        <?php
              function number_format_unlimited_precision($number,$decimal = '.')
              {
                   $broken_number = explode($decimal,$number);
                   return number_format($broken_number[0]).$decimal.$broken_number[1];
              }
        ?>

        Contributed By: MarcM

        For Zero fill - just use the sprintf() function
        $pr_id = 1;
        $pr_id = sprintf("%03d", $pr_id);
        echo $pr_id;
        //outputs 001
        -----------------
        $pr_id = 10;
        $pr_id = sprintf("%03d", $pr_id);
        echo $pr_id;
        //outputs 010
        -----------------
        You can change %03d to %04d, etc.

        PHP ord() Function

        What does ord() do?

        The PHP ord() function will convert the first byte of a string to a value between 0 and 255.

        PHP ord() Syntax

         ord ( string $string ) : int

        PHP ord() Parameters

        1. string — A character.

        PHP ord() Return Value

        The PHP ord() function returns an integer between 0 and 255.

        PHP ord() Working Examples

        1. ord() example

        <?php
        $str = "\n";
        if (ord($str) == 10) {
            echo "The first character of \$str is a line feed.\n";
        }
        ?>

        2. Examining the individual bytes of a UTF-8 string

        <?php
        declare(encoding='UTF-8');
        $str = "🐘";
        for ( $pos=0; $pos < strlen($str); $pos ++ ) {
         $byte = substr($str, $pos);
         echo 'Byte ' . $pos . ' of $str has value ' . ord($byte) . PHP_EOL;
        }
        ?>

        Output of the above code:


        Byte 0 of $str has value 240
        Byte 1 of $str has value 159
        Byte 2 of $str has value 144
        Byte 3 of $str has value 152

        Additional Tips from Fellow Developers

        Contributed By: arglanir+phpnet

        As ord() doesn't work with utf-8, and if you do not have access to mb_* functions, the following function will work well:
        <?php
        function ordutf8($string, &$offset) {
            $code = ord(substr($string, $offset,1)); 
            if ($code >= 128) {        //otherwise 0xxxxxxx
                if ($code < 224) $bytesnumber = 2;                //110xxxxx
                else if ($code < 240) $bytesnumber = 3;        //1110xxxx
                else if ($code < 248) $bytesnumber = 4;    //11110xxx
                $codetemp = $code - 192 - ($bytesnumber > 2 ? 32 : 0) - ($bytesnumber > 3 ? 16 : 0);
                for ($i = 2; $i <= $bytesnumber; $i++) {
                    $offset ++;
                    $code2 = ord(substr($string, $offset, 1)) - 128;        //10xxxxxx
                    $codetemp = $codetemp*64 + $code2;
                }
                $code = $codetemp;
            }
            $offset += 1;
            if ($offset >= strlen($string)) $offset = -1;
            return $code;
        }
        ?>
        $offset is a reference, as it is not easy to split a utf-8 char-by-char. Useful to iterate on a string:
        <?php
        $text = "abcàê߀abc";
        $offset = 0;
        while ($offset >= 0) {
            echo $offset.": ".ordutf8($text, $offset)."\n";
        }
        /* returns:
        0: 97
        1: 98
        2: 99
        3: 224
        5: 234
        7: 223
        9: 8364
        12: 97
        13: 98
        14: 99
        */
        ?>
        Feel free to adapt my code to fit your needs.

        Contributed By: rowan dot collins

        Regarding character sets, and whether or not this is "ASCII". Firstly, there is no such thing as "8-bit ASCII", so if it were ASCII it would only ever return integers up to 127. 8-bit ASCII-compatible encodings include the ISO 8859 family of encodings, which map various common characters to the values from 128 to 255. UTF-8 is also designed so that characters representable in 7-bit ASCII are coded the same; byte values higher than 127 in a UTF-8 string represent the beginning of a multi-byte character.
        In fact, like most of PHP's string functions, this function isn't doing anything to do with character encoding at all - it is just interpreting a binary byte from a string as an unsigned integer. That is, ord(chr(200)) will always return 200, but what character chr(200) *means* will vary depending on what character encoding it is *interpreted* as part of (e.g. during display).
        A technically correct description would be "Returns an integer representation of the first byte of a string, from 0 to 255. For single-byte encodings such as (7-bit) ASCII and the ISO 8859 family, this will correspond to the first character, and will be the position of that character in the encoding's mapping table. For multi-byte encodings, such as UTF-8 or UTF-16, the byte may not represent a complete character."
        The link to asciitable.com should also be replaced by one which explains what character encoding it is displaying, as "Extended ASCII" is an ambiguous and misleading name.

        PHP parse_str() Function

        What does parse_str() do?

        The PHP parse_str() function will parses encoded_string as if it were the query string passed via a URL and sets variables in the current scope (or in the array if result is provided).

        PHP parse_str() Syntax

         parse_str ( string $encoded_string [, array &$result ] ) : void

        PHP parse_str() Parameters

        1. encoded_string — The input string.

        2. result — If the second parameter result is present, variables are stored in this variable as array elements instead.

        PHP parse_str() Return Value

        The PHP parse_str() function returns d.

        PHP parse_str() Working Examples

        1. Using parse_str()

        <?php
        $str = "first=value&arr[]=foo+bar&arr[]=baz";
        // Recommended
        parse_str($str, $output);
        echo $output['first'];  // value
        echo $output['arr'][0]; // foo bar
        echo $output['arr'][1]; // baz
        // DISCOURAGED
        parse_str($str);
        echo $first;  // value
        echo $arr[0]; // foo bar
        echo $arr[1]; // baz
        ?>

        2. parse_str() name mangling

        <?php
        parse_str("My Value=Something");
        echo $My_Value; // Something
        parse_str("My Value=Something", $output);
        echo $output['My_Value']; // Something
        ?>

        Changelog for PHP parse_str() Function

        7.2.0 — Usage of parse_str() without a second parameter now emits an E_DEPRECATED notice.

        Important Points about PHP parse_str() Function

        1. Using this function without the result parameter is highly DISCOURAGED and DEPRECATED as of PHP 7.2.

        2. Dynamically setting variables in function’s scope suffers from exactly same problems as register_globals.

        3. Read section on security of Using Register Globals explaining why it is dangerous.

        4. All variables created (or values returned into array if second parameter is set) are already urldecode()d.

        5. To get the current QUERY_STRING, you may use the variable $_SERVER[‘QUERY_STRING’]. Also, you may want to read the section on variables from external sources.

        6. The magic_quotes_gpc setting affects the output of this function, as parse_str() uses the same mechanism that PHP uses to populate the $_GET, $_POST, etc. variables.

        Additional Tips from Fellow Developers

        Contributed By: Evan K

        It bears mentioning that the parse_str builtin does NOT process a query string in the CGI standard way, when it comes to duplicate fields.  If multiple fields of the same name exist in a query string, every other web processing language would read them into an array, but PHP silently overwrites them:
        <?php
        # silently fails to handle multiple values
        parse_str('foo=1&foo=2&foo=3');
        # the above produces:
        $foo = array('foo' => '3');
        ?>
        Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve the same effect.
        <?php
        # bizarre php-specific behavior
        parse_str('foo[]=1&foo[]=2&foo[]=3');
        # the above produces:
        $foo = array('foo' => array('1', '2', '3') );
        ?>
        This can be confusing for anyone who's used to the CGI standard, so keep it in mind.  As an alternative, I use a "proper" querystring parser function:
        <?php
        function proper_parse_str($str) {
          # result array
          $arr = array();
          # split on outer delimiter
          $pairs = explode('&', $str);
          # loop through each pair
          foreach ($pairs as $i) {
            # split into name and value
            list($name,$value) = explode('=', $i, 2);
            
            # if name already exists
            if( isset($arr[$name]) ) {
              # stick multiple values into an array
              if( is_array($arr[$name]) ) {
                $arr[$name][] = $value;
              }
              else {
                $arr[$name] = array($arr[$name], $value);
              }
            }
            # otherwise, simply stick it in a scalar
            else {
              $arr[$name] = $value;
            }
          }
          # return result array
          return $arr;
        }
        $query = proper_parse_str($_SERVER['QUERY_STRING']);
        ?>

        Contributed By: shagshag

        That's not says in the description but max_input_vars directive affects this function. If there are more input variables on the string than specified by this directive, an E_WARNING is issued, and further input variables are truncated from the request.

        Contributed By: Olivier Mengué

        Vladimir: the function is OK in how it deals with &amp;.
        &amp; must only be used when outputing URLs in HTML/XML data.
        You should ask yourself why you have &amp; in your URL when you give it to parse_str.

        PHP print() Function

        What does print() do?

        The PHP print() function will outputs arg.

        PHP print() Syntax

         print ( string $arg ) : int

        PHP print() Parameters

        1. arg — The input data.

        PHP print() Return Value

        The PHP print() function returns 1, always.

        PHP print() Working Examples

        1. print examples

        <?php
        print("Hello World");
        print "print() also works without parentheses.";
        print "This spans
        multiple lines. The newlines will be
        output as well";
        print "This spans\nmultiple lines. The newlines will be\noutput as well.";
        print "escaping characters is done \"Like this\".";
        // You can use variables inside a print statement
        $foo = "foobar";
        $bar = "barbaz";
        print "foo is $foo"; // foo is foobar
        // You can also use arrays
        $bar = array("value" => "foo");
        print "this is {$bar['value']} !"; // this is foo !
        // Using single quotes will print the variable name, not the value
        print 'foo is $foo'; // foo is $foo
        // If you are not using any other characters, you can just print variables
        print $foo;          // foobar
        print <<<END
        This uses the "here document" syntax to output
        multiple lines with $variable interpolation. Note
        that the here document terminator must appear on a
        line with just a semicolon no extra whitespace!
        END;
        ?>

        Additional Tips from Fellow Developers

        Contributed By: user

        Be careful when using print. Since print is a language construct and not a function, the parentheses around the argument is not required.
        In fact, using parentheses can cause confusion with the syntax of a function and SHOULD be omited.
        Most would expect the following behavior:
        <?php
            if (print("foo") && print("bar")) {
                // "foo" and "bar" had been printed
            }
        ?>
        But since the parenthesis around the argument are not required, they are interpretet as part of the argument.
        This means that the argument of the first print is
            ("foo") && print("bar")
        and the argument of the second print is just
            ("bar")
        For the expected behavior of the first example, you need to write: 
        <?php
            if ((print "foo") && (print "bar")) {
                // "foo" and "bar" had been printed
            }
        ?>

        Contributed By: danielxmorris @ gmail dotcom

        I wrote a println function that determines whether a \n or a <br /> should be appended to the line depending on whether it's being executed in a shell or a browser window.  People have probably thought of this before but I thought I'd post it anyway - it may help a couple of people.
        <?php
        function println ($string_message) {
            $_SERVER['SERVER_PROTOCOL'] ? print "$string_message<br />" : print "$string_message\n";
        }
        ?>
        Examples:
        Running in a browser:
        <?php println ("Hello, world!"); ?>
        Output: Hello, world!<br />
        Running in a shell:
        <?php println ("Hello, world!"); ?>
        Output: Hello, world!\n

        PHP printf() Function

        What does printf() do?

        The PHP printf() function will produces output according to format.

        PHP printf() Syntax

         printf ( string $format [, mixed $... ] ) : int

        PHP printf() Parameters

        1. format — The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result and conversion specifications, each of which results in fetching its own parameter.

        2. ...

        PHP printf() Return Value

        The PHP printf() function returns the length of the outputted string.

        PHP printf() Working Examples

        1. printf(): various examples

        <?php
        $n =  43951789;
        $u = -43951789;
        $c = 65; // ASCII 65 is 'A'
        // notice the double %%, this prints a literal '%' character
        printf("%%b = '%b'\n", $n); // binary representation
        printf("%%c = '%c'\n", $c); // print the ascii character, same as chr() function
        printf("%%d = '%d'\n", $n); // standard integer representation
        printf("%%e = '%e'\n", $n); // scientific notation
        printf("%%u = '%u'\n", $n); // unsigned integer representation of a positive integer
        printf("%%u = '%u'\n", $u); // unsigned integer representation of a negative integer
        printf("%%f = '%f'\n", $n); // floating point representation
        printf("%%o = '%o'\n", $n); // octal representation
        printf("%%s = '%s'\n", $n); // string representation
        printf("%%x = '%x'\n", $n); // hexadecimal representation (lower-case)
        printf("%%X = '%X'\n", $n); // hexadecimal representation (upper-case)
        printf("%%+d = '%+d'\n", $n); // sign specifier on a positive integer
        printf("%%+d = '%+d'\n", $u); // sign specifier on a negative integer
        ?>

        Output of the above code:

        %b = '10100111101010011010101101'
        %c = 'A'
        %d = '43951789'
        %e = '4.39518e+7'
        %u = '43951789'
        %u = '4251015507'
        %f = '43951789.000000'
        %o = '247523255'
        %s = '43951789'
        %x = '29ea6ad'
        %X = '29EA6AD'
        %+d = '+43951789'
        %+d = '-43951789'

        2. printf(): string specifiers

        <?php
        $s = 'monkey';
        $t = 'many monkeys';
        printf("[%s]\n",      $s); // standard string output
        printf("[%10s]\n",    $s); // right-justification with spaces
        printf("[%-10s]\n",   $s); // left-justification with spaces
        printf("[%010s]\n",   $s); // zero-padding works on strings too
        printf("[%'#10s]\n",  $s); // use the custom padding character '#'
        printf("[%10.9s]\n", $t); // right-justification but with a cutoff of 8 characters
        printf("[%-10.9s]\n", $t); // left-justification but with a cutoff of 8 characters
        ?>

        Output of the above code:

         
        [monkey]
        [ monkey]
        [monkey ]
        [0000monkey]
        [####monkey]
        [ many monk]
        [many monk ]

        Important Points about PHP printf() Function

        1. The c type specifier ignores padding and width

        2. Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

        PHP quoted_printable_decode() Function

        What does quoted_printable_decode() do?

        The PHP quoted_printable_decode() function will convert a quoted-printable string to an 8 bit string.

        PHP quoted_printable_decode() Syntax

         quoted_printable_decode ( string $str ) : string

        PHP quoted_printable_decode() Parameters

        1. str — The input string.

        PHP quoted_printable_decode() Return Value

        The PHP quoted_printable_decode() function returns the 8-bit binary string.

        PHP quoted_printable_encode() Function

        What does quoted_printable_encode() do?

        The PHP quoted_printable_encode() function will convert a 8 bit string to a quoted-printable string.

        PHP quoted_printable_encode() Syntax

         quoted_printable_encode ( string $str ) : string

        PHP quoted_printable_encode() Parameters

        1. str — The input string.

        PHP quoted_printable_encode() Return Value

        The PHP quoted_printable_encode() function returns the encoded string.

        PHP quotemeta() Function

        What does quotemeta() do?

        The PHP quotemeta() function will give you a version of str with a backslash character (\) before every character that is among these:

        PHP quotemeta() Syntax

         quotemeta ( string $str ) : string

        PHP quotemeta() Parameters

        1. str — The input string.

        PHP quotemeta() Return Value

        The PHP quotemeta() function returns the string with meta characters quoted, or FALSE if an empty string is given as str.

        PHP rtrim() Function

        What does rtrim() do?

        The PHP rtrim() function will strip whitespace (or other characters) from the end of a string.

        PHP rtrim() Syntax

         rtrim ( string $str [, string $character_mask ] ) : string

        PHP rtrim() Parameters

        1. str — The input string.

        2. character_mask — You can also specify the characters you want to strip, by means of the character_mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

        PHP rtrim() Return Value

        The PHP rtrim() function returns the modified string.

        PHP rtrim() Working Examples

        1. Usage example of rtrim()

        <?php
        $text = "\t\tThese are a few words :) ...  ";
        $binary = "\x09Example string\x0A";
        $hello  = "Hello World";
        var_dump($text, $binary, $hello);
        print "\n";
        $trimmed = rtrim($text);
        var_dump($trimmed);
        $trimmed = rtrim($text, " \t.");
        var_dump($trimmed);
        $trimmed = rtrim($hello, "Hdle");
        var_dump($trimmed);
        // trim the ASCII control characters at the end of $binary
        // (from 0 to 31 inclusive)
        $clean = rtrim($binary, "\x00..\x1F");
        var_dump($clean);
        ?>

        Output of the above code:

        string(32) " These are a few words :) ... "
        string(16) " Example string
        "
        string(11) "Hello World"
        string(30) " These are a few words :) ..."
        string(26) " These are a few words :)"
        string(9) "Hello Wor"
        string(15) " Example string"

        Additional Tips from Fellow Developers

        Contributed By: pinkgothic

        I have an obsessive love for php's array functions given how extremely easy they've made complex string handling for me in various situations... so, have another string-rtrim() variant: 
         
        <?php 
         
        function strrtrim($message, $strip) { 
            // break message apart by strip string 
            $lines = explode($strip, $message); 
            $last  = ''; 
            // pop off empty strings at the end 
            do { 
                $last = array_pop($lines); 
            } while (empty($last) && (count($lines))); 
            // re-assemble what remains 
            return implode($strip, array_merge($lines, array($last))); 
        } 
         
        ?> 
         
        Astonishingly, something I didn't expect, but: It completely compares to harmor's rstrtrim below, execution time wise. o_o Whee!

        Contributed By: gbelanger

        True, the Perl chomp() will only trim newline characters. There is, however, the Perl chop() function which is pretty much identical to the PHP rtrim() 
         
        --- 
         
        Here's a quick way to recursively trim every element of an array, useful after the file() function : 
         
        <?php 
        # Reads /etc/passwd file an trims newlines on each entry 
        $aFileContent = file("/etc/passwd"); 
        foreach ($aFileContent as $sKey => $sValue) { 
            $aFileContent[$sKey] = rtrim($sValue); 
        } 
         
        print_r($aFileContent); 
        ?>

        Contributed By: todd

        This shows how rtrim works when using the optional charlist parameter:
        rtrim reads a character, one at a time, from the optional charlist parameter and compares it to the end of the str string. If the characters match, it trims it off and starts over again, looking at the "new" last character in the str string and compares it to the first character in the charlist again. If the characters do not match, it moves to the next character in the charlist parameter comparing once again. It continues until the charlist parameter has been completely processed, one at a time, and the str string no longer contains any matches. The newly "rtrimmed" string is returned.
        <?php
          // Example 1:
          rtrim('This is a short short sentence', 'short sentence');
          // returns 'This is a'
          // If you were expecting the result to be 'This is a short ',
          // then you're wrong; the exact string, 'short sentence',
          // isn't matched.  Remember, character-by-character comparison!
          // Example 2:
          rtrim('This is a short short sentence', 'cents');
          // returns 'This is a short short '
        ?>

        Contributed By: pinkgothic

        On the recurring subject of string-stripping instead of character-stripping rtrim() implementations... the simplest (with a caveat) is probably the basename() function. It has a second parameter that functions as a right-trim using whole strings:
        <?php
        echo basename('MooFoo', 'Foo');
        ?>
        ...outputs 'Moo'.
        Since it also strips anything that looks like a directory, it's not quite identical with hacking a string off the end:
        <?php
        echo basename('Zoo/MooFoo', 'Foo');
        ?>
        ...still outputs 'Moo'.
        But sometimes it gets the job done.

        Contributed By: Unimagined

        I needed a way to trim all white space and then a few chosen strings from the end of a string.  So I wrote this class to reuse when stuff needs to be trimmed.  
        <?php
        class cleaner {
        function cleaner ($cuts,$pinfo) {
        $ucut = "0";
        $lcut = "0";
        while ($cuts[$ucut]) {
        $lcut++;
        $ucut++;
        }
        $lcut = $lcut - 1;
        $ucut = "0";
        $rcut = "0";
        $wiy = "start";
        while ($wiy) {
        if ($so) {
        $ucut = "0";
        $rcut = "0";
        unset($so);
        }
        if (!$cuts[$ucut]) {
        $so = "restart";
        } else {
        $pinfo = rtrim($pinfo);
        $bpinfol = strlen($pinfo);
        $tcut = $cuts[$ucut];
        $pinfo = rtrim($pinfo,"$tcut");
        $pinfol = strlen($pinfo);
            if ($bpinfol == $pinfol) {
            $rcut++;
            if ($rcut == $lcut) {
            unset($wiy);
            }
            $ucut++;
            } else {
            $so = "restart";
            }
        }
        }
        $this->cleaner = $pinfo;
        }
        }
        $pinfo = "Well... I'm really bored...<br /><br>&nbsp;    \n\t&nbsp;<br><br /><br>&nbsp;    \r\r&nbsp;<br>\r<br /><br>\r&nbsp;    &nbsp;\n<br>      <br />\t";
        $cuts = array('\n','\r','\t',' ',' ','&nbsp;','<br />','<br>','<br/>');
        $pinfo = new cleaner($cuts,$pinfo);
        $pinfo = $pinfo->cleaner;
        print $pinfo;
        ?>
        That class will take any string that you put in the $cust array and remove it from the end of the $pinfo string.  It's useful for cleaning up comments, articles, or mail that users post to your site, making it so there's no extra blank space or blank lines.

        PHP setlocale() Function

        What does setlocale() do?

        The PHP setlocale() function will sets locale information.

        PHP setlocale() Syntax

         setlocale ( int $category , string $locale [, string $... ] ) : string
         setlocale ( int $category , array $locale ) : string

        PHP setlocale() Parameters

        1. category — category is a named constant specifying the category of the functions affected by the locale setting:

        2. locale — If locale is NULL or the empty string “”, the locale names will be set from the values of environment variables with the same names as the above categories, or from “LANG”.

        3. ... — (Optional string or array parameters to try as locale settings until success.)

        PHP setlocale() Return Value

        The PHP setlocale() function returns the new current locale, or FALSE if the locale functionality is not implemented on your platform, the specified locale does not exist or the category name is invalid.

        PHP setlocale() Working Examples

        1. setlocale() Examples

        <?php
        /* Set locale to Dutch */
        setlocale(LC_ALL, 'nl_NL');
        /* Output: vrijdag 22 december 1978 */
        echo strftime("%A %e %B %Y", mktime(0, 0, 0, 12, 22, 1978));
        /* try different possible locale names for german */
        $loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge');
        echo "Preferred locale for german on this system is '$loc_de'";
        ?>

        2. setlocale() Examples for Windows

        <?php
        /* Set locale to Dutch */
        setlocale(LC_ALL, 'nld_nld');
        /* Output: vrijdag 22 december 1978 */
        echo strftime("%A %d %B %Y", mktime(0, 0, 0, 12, 22, 1978));
        /* try different possible locale names for german */
        $loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
        echo "Preferred locale for german on this system is '$loc_de'";
        ?>

        Changelog for PHP setlocale() Function

        7.0.0 — Support for the category parameter passed as a string has been removed. Only LC_* constants can be used as of this version.

        5.3.0 — This function now throws an E_DEPRECATED notice if a string is passed to the category parameter instead of one of the LC_* constants.

        Important Points about PHP setlocale() Function

        1. The locale information is maintained per process, not per thread. If you are running PHP on a multithreaded server API like IIS, HHVM or Apache on Windows, you may experience sudden changes in locale settings while a script is running, though the script itself never called setlocale(). This happens due to other scripts running in different threads of the same process at the same time, changing the process-wide locale using setlocale().

        2. On Windows, setlocale(LC_ALL, ”) sets the locale names from the system’s regional/language settings (accessible via Control Panel).

        3. The return value of setlocale() depends on the system that PHP is running. It returns exactly what the system setlocale function returns.

        Additional Tips from Fellow Developers

        Contributed By: r dot nospam dot velseboer

        Be careful with the LC_ALL setting, as it may introduce some unwanted conversions. For example, I used 
        setlocale (LC_ALL, "Dutch");
        to get my weekdays in dutch on the page. From that moment on (as I found out many hours later) my floating point values from MYSQL where interpreted as integers because the Dutch locale wants a comma (,) instead of a point (.) before the decimals. I tried printf, number_format, floatval.... all to no avail. 1.50 was always printed as 1.00 :(
        When I set my locale to :
         setlocale (LC_TIME, "Dutch");
        my weekdays are good now and my floating point values too. 
        I hope I can save some people the trouble of figuring this out by themselves.
        Rob

        Contributed By: russ

        If you are looking for a getlocale() function simply pass 0 (zero) as the second parameter to setlocale().
        Beware though if you use the category LC_ALL and some of the locales differ as a string containing all the locales is returned:
        <?php
        echo setlocale(LC_ALL, 0);
        // LC_CTYPE=en_US.UTF-8;LC_NUMERIC=C;LC_TIME=C;LC_COLLATE=C;LC_MONETARY=C;LC_MESSAGES=C;LC_PAPER=C;LC_NAME=C;
        // LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=C;LC_IDENTIFICATION=C
        echo setlocale(LC_CTYPE, 0);
        // en_US.UTF-8
        setlocale(LC_ALL, "en_US.UTF-8");
        echo setlocale(LC_ALL, 0);
        // en_US.UTF-8
        ?>
        If you are looking to store and reset the locales you could do something like this:
        <?php
        $originalLocales = explode(";", setlocale(LC_ALL, 0));
        setlocale(LC_ALL, "nb_NO.utf8");
        // Do something
        foreach ($originalLocales as $localeSetting) {
          if (strpos($localeSetting, "=") !== false) {
            list ($category, $locale) = explode("=", $localeSetting);
          }
          else {
            $category = LC_ALL;
            $locale   = $localeSetting;
          }
          setlocale($category, $locale); 
        }
        ?>
        The above works here (Ubuntu Linux) but as the setlocale() function is just wrapping the equivalent system calls, your mileage may vary on the result.

        Contributed By: Kari Sderholm aka Haprog

        It took me a while to figure out how to get a Finnish locale correctly set on Ubuntu Server with Apache2 and PHP5.
        At first the output for "locale -a" was this:
        C
        en_US.utf8
        POSIX
        I had to install a finnish language pack with
        "sudo apt-get install language-pack-fi-base"
        Now the output for "locale -a" is:
        C
        en_US.utf8
        fi_FI.utf8
        POSIX
        The last thing you need to do after installing the correct language pack is restart Apache with "sudo apache2ctl restart". The locale "fi_FI.utf8" can then be used in PHP5 after restarting Apache.
        For setting Finnish timezone and locale in PHP use:
        <?php
        date_default_timezone_set('Europe/Helsinki');
        setlocale(LC_ALL, array('fi_FI.UTF-8','fi_FI@euro','fi_FI','finnish'));
        ?>

        PHP sha1() Function

        What does sha1() do?

        The PHP sha1() function will calculates the sha1 hash of str using the » US Secure Hash Algorithm 1.

        PHP sha1() Syntax

         sha1 ( string $str [, bool $raw_output = FALSE ] ) : string

        PHP sha1() Parameters

        1. str — The input string.

        2. raw_output — If the optional raw_output is set to TRUE, then the sha1 digest is instead returned in raw binary format with a length of 20, otherwise the returned value is a 40-character hexadecimal number.

        PHP sha1() Return Value

        The PHP sha1() function returns the sha1 hash as a string.

        PHP sha1() Working Examples

        1. A sha1() example

        <?php
        $str = 'apple';
        if (sha1($str) === 'd0be2dc421be4fcd0172e5afceea3970e2f3d940') {
            echo "Would you like a green or red apple?";
        }
        ?>

        Important Points about PHP sha1() Function

        1. It is not recommended to use this function to secure passwords, due to the fast nature of this hashing algorithm. See the Password Hashing FAQ for details and best practices.

        Additional Tips from Fellow Developers

        Contributed By:

        The suggestion below to double-hash your password is not a good idea.  You are much much better off adding a variable salt to passwords before hashing (such as the username or other field that is dissimilar for every account).
        Double hashing is *worse* security than a regular hash.  What you're actually doing is taking some input $passwd, converting it to a string of exactly 32 characters containing only the characters [0-9][A-F], and then hashing *that*. You have just *greatly* increased the odds of a hash collision (ie. the odds that I can guess a phrase that will hash to the same value as your password).
        sha1(md5($pass)) makes even less sense, since you're feeding in 128-bits of information to generate a 256-bit hash, so 50% of the resulting data is redundant.  You have not increased security at all.

        PHP sha1_file() Function

        What does sha1_file() do?

        The PHP sha1_file() function will give you that hash. The hash is a 40-character hexadecimal number.

        PHP sha1_file() Syntax

         sha1_file ( string $filename [, bool $raw_output = FALSE ] ) : string

        PHP sha1_file() Parameters

        1. filename — The filename of the file to hash.

        2. raw_output — When TRUE, returns the digest in raw binary format with a length of 20.

        PHP sha1_file() Return Value

        The PHP sha1_file() function returns a string on success, FALSE otherwise.

        PHP sha1_file() Working Examples

        1. sha1_file() example

        <?php
        foreach(glob('/home/Kalle/myproject/*.php') as $ent)
        {
            if(is_dir($ent))
            {
                continue;
            }
            echo $ent . ' (SHA1: ' . sha1_file($ent) . ')', PHP_EOL;
        }
        ?>

        Changelog for PHP sha1_file() Function

        5.1.0 — Changed the function to use the streams API. It means that you can use it with wrappers, like sha1_file(‘http://example.com/..’)

        Additional Tips from Fellow Developers

        Contributed By: xijque

        Just for the record - 
        As some have pointed out, you have two ways to generate the hash of a file:
        Method 1 [this function]: sha1_file($file)
        Method 2: sha1(file_get_contents($file))
        It's important to realize that these two methods are NOT the same thing. If they were, I seriously doubt this function would exist.
        The key difference, as far as I can tell, is how the file's contents are loaded. The second method loads the entirety of $file into memory before passing it to sha1($str). Method two, however, loads the contents of $file as they are needed to create the hash.
        If you can guarantee that you'll only ever have to hash relatively small files, this difference means very little. If you have larger ones, though, loading the entirety of file into memory is a bad idea: best case, you slow down your server as it tries to handle the request; worse case, you run out of memory and don't get your hash at all.
        Just try to keep this in mind if you decide to load the file's contents yourself, in lieu of using this function. On my system, I was able to use this function to generate the hash of a 2.6GB file in 22 seconds, whereas I could not with the second method, due to an out-of-memory error (which took 185 seconds).

        PHP similar_text() Function

        What does similar_text() do?

        The PHP similar_text() function will calculate the similarity between two strings.

        PHP similar_text() Syntax

         similar_text ( string $first , string $second [, float &$percent ] ) : int

        PHP similar_text() Parameters

        1. first — The first string.

        2. second — The second string.

        3. percent — By passing a reference as third argument, similar_text() will calculate the similarity in percent, by dividing the result of similar_text() by the average of the lengths of the given strings times 100.

        PHP similar_text() Return Value

        The PHP similar_text() function returns the number of matching chars in both strings.

        PHP similar_text() Working Examples

        1. similar_text() argument swapping example

        first

        Output of the above code:

        similarity: 5 (71.428571428571 %)
        similarity: 3 (42.857142857143 %)

        Important Points about PHP similar_text() Function

        1. Swapping the first and second may yield a different result; see the example below.

        Additional Tips from Fellow Developers

        Contributed By:

        Hey there, 
         
        Be aware when using this function, that the order of passing the strings is very important if you want to calculate the percentage of similarity, in fact, altering the variables will give a very different result, example : 
         
        <?php 
        $var_1 = 'PHP IS GREAT'; 
        $var_2 = 'WITH MYSQL'; 
         
        similar_text($var_1, $var_2, $percent); 
         
        echo $percent; 
        // 27.272727272727 
         
        similar_text($var_2, $var_1, $percent); 
         
        echo $percent; 
        // 18.181818181818 
        ?>

        Contributed By: daniel dot karbach

        Please note that this function calculates a similarity of 0 (zero) for two empty strings.
        <?php
        similar_text("", "", $sim);
        echo $sim; // "0"
        ?>

        Contributed By: vasyl

        Recursive algorithm usually is very elegant one. I found a way to get better precision without the recursion. Imagine two different (or same) length ribbons with letters on each. You simply shifting one ribbon to left till it matches the letter the first.
        <?php
        function similarity($str1, $str2) {
            $len1 = strlen($str1);
            $len2 = strlen($str2);
            
            $max = max($len1, $len2);
            $similarity = $i = $j = 0;
            
            while (($i < $len1) && isset($str2[$j])) {
                if ($str1[$i] == $str2[$j]) {
                    $similarity++;
                    $i++;
                    $j++;
                } elseif ($len1 < $len2) {
                    $len1++;
                    $j++;
                } elseif ($len1 > $len2) {
                    $i++;
                    $len1--;
                } else {
                    $i++;
                    $j++;
                }
            }
            return round($similarity / $max, 2);
        }
        $str1 = '12345678901234567890';
        $str2 = '12345678991234567890';
        echo 'Similarity: ' . (similarity($str1, $str2) * 100) . '%';
        ?>

        Contributed By: ryan

        Note that this function is case sensitive:
        <?php
        $var1 = 'Hello';
        $var2 = 'Hello';
        $var3 = 'hello';
        echo similar_text($var1, $var2);  // 5
        echo similar_text($var1, $var3);  // 4

        PHP soundex() Function

        What does soundex() do?

        The PHP soundex() function will calculates the soundex key of str.

        PHP soundex() Syntax

         soundex ( string $str ) : string

        PHP soundex() Parameters

        1. str — The input string.

        PHP soundex() Return Value

        The PHP soundex() function returns the soundex key as a string.

        PHP soundex() Working Examples

        1. Soundex Examples

        <?php
        soundex("Euler")       == soundex("Ellery");    // E460
        soundex("Gauss")       == soundex("Ghosh");     // G200
        soundex("Hilbert")     == soundex("Heilbronn"); // H416
        soundex("Knuth")       == soundex("Kant");      // K530
        soundex("Lloyd")       == soundex("Ladd");      // L300
        soundex("Lukasiewicz") == soundex("Lissajous"); // L222
        ?>

        Additional Tips from Fellow Developers

        Contributed By: nicolas dot zimmer

        Since soundex() does not produce optimal results for German language
        we have written a function to implement the so called Kölner Phonetik
        (Cologne Phonetic).
        Please find the code below in the hope it might be useful:
        <?php
        /**
         * A function for retrieving the Kölner Phonetik value of a string
         * 
         * As described at http://de.wikipedia.org/wiki/Kölner_Phonetik
         * Based on Hans Joachim Postel: Die Kölner Phonetik. 
         * Ein Verfahren zur Identifizierung von Personennamen auf der 
         * Grundlage der Gestaltanalyse. 
         * in: IBM-Nachrichten, 19. Jahrgang, 1969, S. 925-931
         * 
         * This program is distributed in the hope that it will be useful,
         * but WITHOUT ANY WARRANTY; without even the implied warranty of
         * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
         * GNU General Public License for more details.
         *
         * @package phonetics
         * @version 1.0
         * @link http://www.einfachmarke.de
         * @license GPL 3.0 <http://www.gnu.org/licenses/>
         * @copyright  2008 by einfachmarke.de
         * @author Nicolas Zimmer <nicolas dot zimmer at einfachmarke.de>
         */
        function cologne_phon($word){
            
          /**
          * @param  string  $word string to be analyzed
          * @return string  $value represents the Kölner Phonetik value
          * @access public
          */
          
            //prepare for processing
            $word=strtolower($word);
            $substitution=array(
                    "ä"=>"a",
                    "ö"=>"o",
                    "ü"=>"u",
                    "ß"=>"ss",
                    "ph"=>"f"
                    );
            foreach ($substitution as $letter=>$substitution) {
                $word=str_replace($letter,$substitution,$word);
            }
            
            $len=strlen($word);
            
            //Rule for exeptions
            $exceptionsLeading=array(
            4=>array("ca","ch","ck","cl","co","cq","cu","cx"),
            8=>array("dc","ds","dz","tc","ts","tz")
            );
            
            $exceptionsFollowing=array("sc","zc","cx","kx","qx");
            
            //Table for coding
            $codingTable=array(
            0=>array("a","e","i","j","o","u","y"),
            1=>array("b","p"),
            2=>array("d","t"),
            3=>array("f","v","w"),
            4=>array("c","g","k","q"),
            48=>array("x"),
            5=>array("l"),
            6=>array("m","n"),
            7=>array("r"),
            8=>array("c","s","z"),
            );
            
            for ($i=0;$i<$len;$i++){
                $value[$i]="";
                
                //Exceptions
                if ($i==0 AND $word[$i].$word[$i+1]=="cr") $value[$i]=4;
                
                foreach ($exceptionsLeading as $code=>$letters) {
                    if (in_array($word[$i].$word[$i+1],$letters)){
                            $value[$i]=$code;
        }                }
                
                if ($i!=0 AND (in_array($word[$i-1].$word[$i], 
        $exceptionsFollowing))) {
                    value[$i]=8;        
        }                
                
                //Normal encoding
                if ($value[$i]==""){
                        foreach ($codingTable as $code=>$letters) {
                            if (in_array($word[$i],$letters))$value[$i]=$code;
                        }
                    }
                }
            
            //delete double values
            $len=count($value);
            
            for ($i=1;$i<$len;$i++){
                if ($value[$i]==$value[$i-1]) $value[$i]="";
            }
            
            //delete vocals 
            for ($i=1;$i>$len;$i++){//omitting first characer code and h
                if ($value[$i]==0) $value[$i]="";
            }
            
            
            $value=array_filter($value);
            $value=implode("",$value);
            
            return $value;
            
        }
        ?>

        Contributed By: Dirk Hoeschen – Feenders de

        I made some improvements to the "Cologne Phonetic" function of niclas zimmer. Key and value of the arrays are inverted to uses simple arrays instead of multidimensional arrays. Therefore all loops and iterations are not longer necessary to find the matching value  for a char.
        I put the function into a static class and moved the array declarations outside the function.
        The result is more reliable and five times faster than the original.
        <?php   
        class CologneHash() {
            static $eLeading = array("ca" => 4, "ch" => 4, "ck" => 4, "cl" => 4, "co" => 4, "cq" => 4, "cu" => 4, "cx" => 4, "dc" => 8, "ds" => 8, "dz" => 8, "tc" => 8, "ts" => 8, "tz" => 8); 
            static $eFollow = array("sc", "zc", "cx", "kx", "qx");
            static $codingTable = array("a" => 0, "e" => 0, "i" => 0, "j" => 0, "o" => 0, "u" => 0, "y" => 0,
                "b" => 1, "p" => 1, "d" => 2, "t" => 2, "f" => 3, "v" => 3, "w" => 3, "c" => 4, "g" => 4, "k" => 4, "q" => 4,
                "x" => 48, "l" => 5, "m" => 6, "n" => 6, "r" => 7, "c" => 8, "s" => 8, "z" => 8);
            public static function getCologneHash($word)
            {
                if (empty($word)) return false;
                $len = strlen($word);
         
                for ($i = 0; $i < $len; $i++) {
                    $value[$i] = "";
         
                    //Exceptions
                    if ($i == 0 && $word[$i] . $word[$i + 1] == "cr") {
                        $value[$i] = 4;
                    }
         
                    if (isset($word[$i + 1]) && isset(self::$eLeading[$word[$i] . $word[$i + 1]])) {
                        $value[$i] = self::$eLeading[$word[$i] . $word[$i + 1]];
                    }
                    if ($i != 0 && (in_array($word[$i - 1] . $word[$i], self::$eFollow))) {
                        $value[$i] = 8;
                    }
         
                    // normal encoding
                    if ($value[$i]=="") {
                        if (isset(self::$codingTable[$word[$i]])) {
                            $value[$i] = self::$codingTable[$word[$i]];
                        }
                    }
                }
                // delete double values
                $len = count($value);
         
                for ($i = 1; $i < $len; $i++) {
                    if ($value[$i] == $value[$i - 1]) {
                        $value[$i] = "";
                    }
                }
         
                // delete vocals
                for ($i = 1; $i > $len; $i++) {
                    // omitting first characer code and h
                    if ($value[$i] == 0) {
                        $value[$i] = "";
                    }
                }
         
                $value = array_filter($value);
                $value = implode("", $value);
         
                return $value;
            }
         
        }
        ?>

        PHP sprintf() Function

        What does sprintf() do?

        The PHP sprintf() function will give you a string produced according to the formatting string format.

        PHP sprintf() Syntax

         sprintf ( string $format [, mixed $... ] ) : string

        PHP sprintf() Parameters

        1. format — The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result and conversion specifications, each of which results in fetching its own parameter.

        2. ...

        PHP sprintf() Return Value

        The PHP sprintf() function returns a string produced according to the formatting string format, or FALSE on failure.

        PHP sprintf() Working Examples

        1. Argument swapping

        <?php
        $num = 5;
        $location = 'tree';
        $format = 'There are %d monkeys in the %s';
        echo sprintf($format, $num, $location);
        ?>

        Output of the above code:

        There are 5 monkeys in the tree

        2. Specifying padding character

        <?php
        echo sprintf("%'.9d\n", 123);
        echo sprintf("%'.09d\n", 123);
        ?>

        Output of the above code:

        ......123
        000000123

        3. Position specifier with other specifiers

        <?php
        $format = 'The %2$s contains %1$04d monkeys';
        echo sprintf($format, $num, $location);
        ?>

        Output of the above code:

        The tree contains 0005 monkeys

        4. sprintf(): zero-padded integers

        <?php
        $isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
        ?>

        5. sprintf(): formatting currency

        <?php
        $money1 = 68.75;
        $money2 = 54.35;
        $money = $money1 + $money2;
        echo $money;
        echo "\n";
        $formatted = sprintf("%01.2f", $money);
        echo $formatted;
        ?>

        Output of the above code:

        123.1
        123.10

        6. sprintf(): scientific notation

        <?php
        $number = 362525200;
        echo sprintf("%.3e", $number);
        ?>

        Output of the above code:

        3.625e+8

        Important Points about PHP sprintf() Function

        1. The c type specifier ignores padding and width

        2. Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

        Additional Tips from Fellow Developers

        Contributed By: Alex R. Gibbs

        1.  A plus sign ('+') means put a '+' before positive numbers while a minus sign ('-') means left justify.  The documentation incorrectly states that they are interchangeable.  They produce unique results that can be combined:
        <?php
        echo sprintf ("|%+4d|%+4d|\n",   1, -1);
        echo sprintf ("|%-4d|%-4d|\n",   1, -1);
        echo sprintf ("|%+-4d|%+-4d|\n", 1, -1);
        ?>
        outputs:
        |  +1|  -1|
        |1   |-1  |
        |+1  |-1  |
        2.  Padding with a '0' is different than padding with other characters.  Zeros will only be added at the front of a number, after any sign.  Other characters will be added before the sign, or after the number:
        <?php
        echo sprintf ("|%04d|\n",   -2);
        echo sprintf ("|%':4d|\n",  -2);
        echo sprintf ("|%-':4d|\n", -2);
        // Specifying both "-" and "0" creates a conflict with unexpected results:
        echo sprintf ("|%-04d|\n",  -2);
        // Padding with other digits behaves like other non-zero characters:
        echo sprintf ("|%-'14d|\n", -2);
        echo sprintf ("|%-'04d|\n", -2);
        ?>
        outputs:
        |-002|
        |::-2|
        |-2::|
        |-2  |
        |-211|
        |-2  |

        Contributed By: remy dot damour

        With printf() and sprintf() functions, escape character is not backslash '\' but rather '%'.
        Ie. to print '%' character you need to escape it with itself:
        <?php
        printf('%%%s%%', 'koko'); #output: '%koko%'
        ?>

        Contributed By: kontakt

        There are already some comments on using sprintf to force leading leading zeros but the examples only include integers. I needed leading zeros on floating point numbers and was surprised that it didn't work as expected.
        Example:
        <?php
        sprintf('%02d', 1);
        ?>
        This will result in 01. However, trying the same for a float with precision doesn't work:
        <?php
        sprintf('%02.2f', 1);
        ?>
        Yields 1.00. 
        This threw me a little off. To get the desired result, one needs to add the precision (2) and the length of the decimal seperator "." (1). So the correct pattern would be
        <?php
        sprintf('%05.2f', 1);
        ?>
        Output: 01.00
        Please see http://stackoverflow.com/a/28739819/413531 for a more detailed explanation.

        Contributed By: jfgrissom

        I had a nightmare trying to find the two's complement of a 32 bit number.
        I got this from http://www.webmasterworld.com/forum88/13334.htm (credit where credit is due... =P  )
        Quote: ...find out the 2's complement of any number, which is -(pow(2, n) - N) where n is the number of bits and N is the number for which to find out its 2's complement.
        This worked magic for me... previously I was trying to use
        sprintf ("%b",$32BitDecimal);
        But it always returned 10000000000000000000000 when the $32BitDecimal value got above 2,000,000,000.
        This -(pow(2, n) - N)
        Worked remarkably well and was very accurate.
        Hope this helps someone fighting with two's complement in PHP.

        Contributed By: Jay Gilford

        I created this function a while back to save on having to combine mysql_real_escape_string onto all the params passed into a sprintf. it works literally the same as the sprintf other than that it doesn't require you to escape your inputs. Hope its of some use to people
        <?php
        function mressf()
        {
            $args = func_get_args();
            if (count($args) < 2)
                return false;
            $query = array_shift($args);
            $args = array_map('mysql_real_escape_string', $args);
            array_unshift($args, $query);
            $query = call_user_func_array('sprintf', $args);
            return $query;
        }
        ?>
        Regards
        Jay
        Jaygilford.com

        PHP sscanf() Function

        What does sscanf() do?

        The PHP sscanf() function will parses input from a string according to a format.

        PHP sscanf() Syntax

         sscanf ( string $str , string $format [, mixed &$... ] ) : mixed

        PHP sscanf() Parameters

        1. str — The input string being parsed.

        2. format — The interpreted format for str, which is described in the documentation for sprintf() with following differences:

        3. ... — Optionally pass in variables by reference that will contain the parsed values.

        PHP sscanf() Return Value

        The PHP sscanf() function returns d as an array. Otherwise, if optional parameters are passed, the function will return the number of assigned values. The optional parameters must be passed by reference.

        PHP sscanf() Working Examples

        1. sscanf() Example

        <?php
        // getting the serial number
        list($serial) = sscanf("SN/2350001", "SN/%d");
        // and the date of manufacturing
        $mandate = "January 01 2000";
        list($month, $day, $year) = sscanf($mandate, "%s %d %d");
        echo "Item $serial was manufactured on: $year-" . substr($month, 0, 3) . "-$day\n";
        ?>

        2. sscanf() – using optional parameters

        <?php
        // get author info and generate DocBook entry
        $auth = "24\tLewis Carroll";
        $n = sscanf($auth, "%d\t%s %s", $id, $first, $last);
        echo "<author id='$id'>
            <firstname>$first</firstname>
            <surname>$last</surname>
        </author>\n";
        ?>

        Additional Tips from Fellow Developers

        Contributed By: jon

        This function is a great way to get integer rgb values from the html equivalent hex.
        list($r, $g, $b) = sscanf('00ccff', '%2x%2x%2x');

        Contributed By: mikewillitsgmail.com

        FYI - if you are trying to scan from a string which contains a filename with extension. For instance:
        <?php
        $out = sscanf('file_name.gif', 'file_%s.%s', $fpart1, $fpart2);
        ?>
        The scanned string in the $fpart1 parameter turns out to be 'name.gif' and $fpart2 will be NULL.
        To get around this you can simply replace the "." with a space or another "white-space like" string sequence.
        I didn't see any other comments on regarding string literals which contain a '.' so I thought I'd mention it. The subtle characteristics of having "white-space delimited" content I think can be a source of usage contention. Obviously, another way to go is regular expressions in this instance, but for newer users this may be helpful.
        Just in case someone else spent 10 minutes of frustration like I did. This was seen on PHP Version 5.2.3-1ubuntu6.3.
        Searching the bug reports shows another users misunderstanding: http://bugs.php.net/bug.php?id=7793

        PHP str_getcsv() Function

        What does str_getcsv() do?

        The PHP str_getcsv() function will give you an array containing the fields read.

        PHP str_getcsv() Syntax

         str_getcsv ( string $input [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]] ) : array

        PHP str_getcsv() Parameters

        1. input — The string to parse.

        2. delimiter — Set the field delimiter (one character only).

        3. enclosure — Set the field enclosure character (one character only).

        4. escape — Set the escape character (at most one character). Defaults as a backslash (\) An empty string (“”) disables the proprietary escape mechanism.

        PHP str_getcsv() Return Value

        The PHP str_getcsv() function returns an indexed array containing the fields read.

        Changelog for PHP str_getcsv() Function

        7.4.0 — The escape parameter now interprets an empty string as signal to disable the proprietary escape mechanism. Formerly, an empty string was treated like the default parameter value.

        Important Points about PHP str_getcsv() Function

        1. The locale settings are taken into account by this function. If LC_CTYPE is e.g. en_US.UTF-8, strings in one-byte encodings may be read wrongly by this function.

        Additional Tips from Fellow Developers

        Contributed By: james

        [Editor's Note (cmb): that does not produce the desired results, if fields contain linebreaks.] 
         
        Handy one liner to parse a CSV file into an array 
         
        <?php 
         
        $csv = array_map('str_getcsv', file('data.csv')); 
         
        ?>

        Contributed By: starrychloe

        Based on James' line, this will create an array of associative arrays with the first row column headers as the keys.
        <?php
            $csv = array_map('str_getcsv', file($file));
            array_walk($csv, function(&$a) use ($csv) {
              $a = array_combine($csv[0], $a);
            });
            array_shift($csv); # remove column header
        ?> 
        This will yield something like
            [2] => Array
                (
                    [Campaign ID] => 295095038
                    [Ad group ID] => 22460178158
                    [Keyword ID] => 3993587178

        Contributed By: durik

        As the str_getcsv(), unlike to fgetcsv(), does not parse the rows in CSV string, I have found following easy workaround: 
         
        <?php 
        $Data = str_getcsv($CsvString, "\n"); //parse the rows 
        foreach($Data as &$Row) $Row = str_getcsv($Row, ";"); //parse the items in rows 
        ?> 
         
        Why not use explode() instead of str_getcsv() to parse rows? Because explode() would not treat possible enclosured parts of string or escaped characters correctly.

        Contributed By: Jay Williams

        Here is a quick and easy way to convert a CSV file to an associated array:
        <?php
        /**
         * @link http://gist.github.com/385876
         */
        function csv_to_array($filename='', $delimiter=',')
        {
            if(!file_exists($filename) || !is_readable($filename))
                return FALSE;
            $header = NULL;
            $data = array();
            if (($handle = fopen($filename, 'r')) !== FALSE)
            {
                while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
                {
                    if(!$header)
                        $header = $row;
                    else
                        $data[] = array_combine($header, $row);
                }
                fclose($handle);
            }
            return $data;
        }
        ?>

        Contributed By: Ryan Rubley

        @normadize - that is a nice start, but it fails on situations where a field is empty but quoted (returning a string with one double quote instead of an empty string) and cases like """""foo""""" that should result in ""foo"" but instead return "foo". I also get a row with 1 empty field at the end because of the final CRLF in the CSV. Plus, I don't really like the !!Q!! magic or urlencoding to get around things. Also, \R doesn't work in pcre on any of my php installations.
        Here is my take on this, without anonymous functions (so it works on PHP < 5.3), and without your options (because I believe the only correct way to parse according to the RFC would be $skip_empty_lines = false and $trim_fields = false).
        //parse a CSV file into a two-dimensional array
        //this seems as simple as splitting a string by lines and commas, but this only works if tricks are performed
        //to ensure that you do NOT split on lines and commas that are inside of double quotes.
        function parse_csv($str)
        {
            //match all the non-quoted text and one series of quoted text (or the end of the string)
            //each group of matches will be parsed with the callback, with $matches[1] containing all the non-quoted text,
            //and $matches[3] containing everything inside the quotes
            $str = preg_replace_callback('/([^"]*)("((""|[^"])*)"|$)/s', 'parse_csv_quotes', $str);
            //remove the very last newline to prevent a 0-field array for the last line
            $str = preg_replace('/\n$/', '', $str);
            //split on LF and parse each line with a callback
            return array_map('parse_csv_line', explode("\n", $str));
        }
        //replace all the csv-special characters inside double quotes with markers using an escape sequence
        function parse_csv_quotes($matches)
        {
            //anything inside the quotes that might be used to split the string into lines and fields later,
            //needs to be quoted. The only character we can guarantee as safe to use, because it will never appear in the unquoted text, is a CR
            //So we're going to use CR as a marker to make escape sequences for CR, LF, Quotes, and Commas.
            $str = str_replace("\r", "\rR", $matches[3]);
            $str = str_replace("\n", "\rN", $str);
            $str = str_replace('""', "\rQ", $str);
            $str = str_replace(',', "\rC", $str);
            //The unquoted text is where commas and newlines are allowed, and where the splits will happen
            //We're going to remove all CRs from the unquoted text, by normalizing all line endings to just LF
            //This ensures us that the only place CR is used, is as the escape sequences for quoted text
            return preg_replace('/\r\n?/', "\n", $matches[1]) . $str;
        }
        //split on comma and parse each field with a callback
        function parse_csv_line($line)
        {
            return array_map('parse_csv_field', explode(',', $line));
        }
        //restore any csv-special characters that are part of the data
        function parse_csv_field($field) {
            $field = str_replace("\rC", ',', $field);
            $field = str_replace("\rQ", '"', $field);
            $field = str_replace("\rN", "\n", $field);
            $field = str_replace("\rR", "\r", $field);
            return $field;
        }

        Contributed By: normadize -a- gmail -d- com

        Like some other users here noted, str_getcsv() cannot be used if you want to comply with either the RFC or with most spreadsheet tools like Excel or Google Docs.
        These tools do not escape commas or new lines, but instead place double-quotes (") around the field. If there are any double-quotes in the field, these are escaped with another double-quote (" becomes ""). All this may look odd, but it is what the RFC and most tools do ... 
        For instance, try exporting as .csv a Google Docs spreadsheet (File > Download as > .csv) which has new lines and commas as part of the field values and see how the .csv content looks, then try to parse it using str_getcsv() ... it will spectacularly regardless of the arguments you pass to it.
        Here is a function that can handle everything correctly, and more:
        - doesn't use any for or while loops,
        - it allows for any separator (any string of any length),
        - option to skip empty lines,
        - option to trim fields,
        - can handle UTF8 data too (although .csv files are likely non-unicode).
        Here is the more human readable version of the function:
        <?php
        // returns a two-dimensional array or rows and fields
        function parse_csv ($csv_string, $delimiter = ",", $skip_empty_lines = true, $trim_fields = true)
        {
            $enc = preg_replace('/(?<!")""/', '!!Q!!', $csv_string);
            $enc = preg_replace_callback(
                '/"(.*?)"/s',
                function ($field) {
                    return urlencode(utf8_encode($field[1]));
                },
                $enc
            );
            $lines = preg_split($skip_empty_lines ? ($trim_fields ? '/( *\R)+/s' : '/\R+/s') : '/\R/s', $enc);
            return array_map(
                function ($line) use ($delimiter, $trim_fields) {
                    $fields = $trim_fields ? array_map('trim', explode($delimiter, $line)) : explode($delimiter, $line);
                    return array_map(
                        function ($field) {
                            return str_replace('!!Q!!', '"', utf8_decode(urldecode($field)));
                        },
                        $fields
                    );
                },
                $lines
            );
        }
        ?>
        Since this is not using any loops, you can actually write it as a one-line statement (one-liner).
        Here's the function using just one line of code for the function body, formatted nicely though:
        <?php
        // returns the same two-dimensional array as above, but with a one-liner code
        function parse_csv ($csv_string, $delimiter = ",", $skip_empty_lines = true, $trim_fields = true)
        {
            return array_map(
                function ($line) use ($delimiter, $trim_fields) {
                    return array_map(
                        function ($field) {
                            return str_replace('!!Q!!', '"', utf8_decode(urldecode($field)));
                        },
                        $trim_fields ? array_map('trim', explode($delimiter, $line)) : explode($delimiter, $line)
                    );
                },
                preg_split(
                    $skip_empty_lines ? ($trim_fields ? '/( *\R)+/s' : '/\R+/s') : '/\R/s',
                    preg_replace_callback(
                        '/"(.*?)"/s',
                        function ($field) {
                            return urlencode(utf8_encode($field[1]));
                        },
                        $enc = preg_replace('/(?<!")""/', '!!Q!!', $csv_string)
                    )
                )
            );
        }
        ?>
        Replace !!Q!! with another placeholder if you wish.
        Have fun.

        Contributed By: dejiakala

        I wanted the best of the 2 solutions by james at moss dot io and Jay Williams (csv_to_array()) - create associative array from a CSV file with a header row.
        <?php
        $array = array_map('str_getcsv', file('data.csv'));
        $header = array_shift($array);
        array_walk($array, '_combine_array', $header);
        function _combine_array(&$row, $key, $header) {
          $row = array_combine($header, $row);
        }
        ?>
        Then I thought why not try some benchmarking? I grabbed a sample CSV file with 50,000 rows (10 columns each) and Vulcan Logic Disassembler (VLD) which hooks into the Zend Engine and dumps all the opcodes (execution units) of a script - see http://pecl.php.net/package/vld and example here: http://fabien.potencier.org/article/8/print-vs-echo-which-one-is-faster
        Result: 
        array_walk() and array_map() - 39 opcodes
        csv_to_array() - 69 opcodes

        PHP str_ireplace() Function

        What does str_ireplace() do?

        The PHP str_ireplace() function will case-insensitive version of str_replace().

        PHP str_ireplace() Syntax

         str_ireplace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) : mixed

        PHP str_ireplace() Parameters

        1. search — The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.

        2. replace — The replacement value that replaces found search values. An array may be used to designate multiple replacements.

        3. subject — The string or array being searched and replaced on, otherwise known as the haystack.

        4. count — If passed, this will be set to the number of replacements performed.

        PHP str_ireplace() Return Value

        The PHP str_ireplace() function returns a string or an array of replacements.

        PHP str_ireplace() Working Examples

        1. str_ireplace() example

        <?php
        $bodytag = str_ireplace("%body%", "black", "<body text=%BODY%>");
        echo $bodytag; // <body text=black>
        ?>

        Important Points about PHP str_ireplace() Function

        1. Because str_ireplace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. Example #2 in the str_replace() documentation demonstrates how this may affect you in practice.

        Additional Tips from Fellow Developers

        Contributed By: sawdust

        Here's a different approach to search result keyword highlighting that will match all keyword sub strings in a case insensitive manner and preserve case in the returned text. This solution first grabs all matches within $haystack in a case insensitive manner, and the secondly loops through each of those matched sub strings and applies a case sensitive replace in $haystack. This way each unique (in terms of case) instance of $needle is operated on individually allowing a case sensitive replace to be done in order to preserve the original case of each unique instance of $needle.
        <?php
        function highlightStr($haystack, $needle, $highlightColorValue) {
             // return $haystack if there is no highlight color or strings given, nothing to do.
            if (strlen($highlightColorValue) < 1 || strlen($haystack) < 1 || strlen($needle) < 1) {
                return $haystack;
            }
            preg_match_all("/$needle+/i", $haystack, $matches);
            if (is_array($matches[0]) && count($matches[0]) >= 1) {
                foreach ($matches[0] as $match) {
                    $haystack = str_replace($match, '<span style="background-color:'.$highlightColorValue.';">'.$match.'</span>', $haystack);
                }
            }
            return $haystack;
        }
        ?>

        PHP str_pad() Function

        What does str_pad() do?

        The PHP str_pad() function will pad a string to a certain length with another string.

        PHP str_pad() Syntax

         str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] ) : string

        PHP str_pad() Parameters

        1. input — The input string.

        2. pad_length — If the value of pad_length is negative, less than, or equal to the length of the input string, no padding takes place, and input will be returned.

        3. pad_string — Note: The pad_string may be truncated if the required number of padding characters can’t be evenly divided by the pad_string’s length.

        4. pad_type — Optional argument pad_type can be STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH. If pad_type is not specified it is assumed to be STR_PAD_RIGHT.

        PHP str_pad() Return Value

        The PHP str_pad() function returns the padded string.

        PHP str_pad() Working Examples

        1. str_pad() example

        <?php
        $input = "Alien";
        echo str_pad($input, 10);                      // produces "Alien     "
        echo str_pad($input, 10, "-=", STR_PAD_LEFT);  // produces "-=-=-Alien"
        echo str_pad($input, 10, "_", STR_PAD_BOTH);   // produces "__Alien___"
        echo str_pad($input,  6, "___");               // produces "Alien_"
        echo str_pad($input,  3, "*");                 // produces "Alien"
        ?>

        Important Points about PHP str_pad() Function

        1. The pad_string may be truncated if the required number of padding characters can’t be evenly divided by the pad_string‘s length.

        Additional Tips from Fellow Developers

        Contributed By: Marjune

        Since the default pad_type is STR_PAD_RIGHT. using STR_PAD_BOTH were always favor in the right pad if the required number of padding characters can't be evenly divided. 
        e.g
        <?php
        echo str_pad("input", 10, "pp", STR_PAD_BOTH ); // ppinputppp
        echo str_pad("input", 6, "p", STR_PAD_BOTH ); // inputp
        echo str_pad("input", 8, "p", STR_PAD_BOTH ); //pinputpp
        ?>

        Contributed By:

        A proper unicode string padder;
        <?php
        mb_internal_encoding('utf-8'); // @important
        function str_pad_unicode($str, $pad_len, $pad_str = ' ', $dir = STR_PAD_RIGHT) {
            $str_len = mb_strlen($str);
            $pad_str_len = mb_strlen($pad_str);
            if (!$str_len && ($dir == STR_PAD_RIGHT || $dir == STR_PAD_LEFT)) {
                $str_len = 1; // @debug
            }
            if (!$pad_len || !$pad_str_len || $pad_len <= $str_len) {
                return $str;
            }
            
            $result = null;
            $repeat = ceil($str_len - $pad_str_len + $pad_len);
            if ($dir == STR_PAD_RIGHT) {
                $result = $str . str_repeat($pad_str, $repeat);
                $result = mb_substr($result, 0, $pad_len);
            } else if ($dir == STR_PAD_LEFT) {
                $result = str_repeat($pad_str, $repeat) . $str;
                $result = mb_substr($result, -$pad_len);
            } else if ($dir == STR_PAD_BOTH) {
                $length = ($pad_len - $str_len) / 2;
                $repeat = ceil($length / $pad_str_len);
                $result = mb_substr(str_repeat($pad_str, $repeat), 0, floor($length)) 
                            . $str 
                               . mb_substr(str_repeat($pad_str, $repeat), 0, ceil($length));
            }
            
            return $result;
        }
        ?>
        Test;
        <?php
        // needs ie. "test.php" file encoded in "utf-8 without bom"
        $s = '...';
        for ($i = 3; $i <= 1000; $i++) {
            $s1 = str_pad($s, $i, 'AO', STR_PAD_BOTH); // can not inculde unicode char!!!
            $s2 = str_pad_unicode($s, $i, 'ÄÖ', STR_PAD_BOTH);
            $sl1 = strlen($s1);
            $sl2 = mb_strlen($s2);
            echo  "len $sl1: $s1 \n";
            echo  "len $sl2: $s2 \n";
            echo  "\n";
            if ($sl1 != $sl2) die("Fail!");
        }
        ?>
        Output;
        len 3: ... 
        len 3: ... 
        len 4: ...A 
        len 4: ...Ä 
        len 5: A...A 
        len 5: Ä...Ä 
        len 6: A...AO 
        len 6: Ä...ÄÖ 
        ...

        Contributed By: wes

        Multibyte version:
        <?php
        function mb_str_pad($str, $pad_len, $pad_str = ' ', $dir = STR_PAD_RIGHT, $encoding = NULL)
        {
            $encoding = $encoding === NULL ? mb_internal_encoding() : $encoding;
            $padBefore = $dir === STR_PAD_BOTH || $dir === STR_PAD_LEFT;
            $padAfter = $dir === STR_PAD_BOTH || $dir === STR_PAD_RIGHT;
            $pad_len -= mb_strlen($str, $encoding);
            $targetLen = $padBefore && $padAfter ? $pad_len / 2 : $pad_len;
            $strToRepeatLen = mb_strlen($pad_str, $encoding);
            $repeatTimes = ceil($targetLen / $strToRepeatLen);
            $repeatedString = str_repeat($pad_str, max(0, $repeatTimes)); // safe if used with valid utf-8 strings
            $before = $padBefore ? mb_substr($repeatedString, 0, floor($targetLen), $encoding) : '';
            $after = $padAfter ? mb_substr($repeatedString, 0, ceil($targetLen), $encoding) : '';
            return $before . $str . $after;
        }
        ?>

        PHP str_repeat() Function

        What does str_repeat() do?

        The PHP str_repeat() function will give you input repeated multiplier times.

        PHP str_repeat() Syntax

         str_repeat ( string $input , int $multiplier ) : string

        PHP str_repeat() Parameters

        1. input — The string to be repeated.

        2. multiplier — Number of time the input string should be repeated.

        PHP str_repeat() Return Value

        The PHP str_repeat() function returns the repeated string.

        PHP str_repeat() Working Examples

        1. str_repeat() example

        <?php
        echo str_repeat("-=", 10);
        ?>

        Output of the above code:

        -=-=-=-=-=-=-=-=-=-=

        Additional Tips from Fellow Developers

        Contributed By: Damien Bezborodov

        Here is a simple one liner to repeat a string multiple times with a separator:
        <?php
        implode($separator, array_fill(0, $multiplier, $input));
        ?>
        Example script:
        <?php
        // How I like to repeat a string using standard PHP functions
        $input = 'bar';
        $multiplier = 5;
        $separator = ',';
        print implode($separator, array_fill(0, $multiplier, $input));
        print "\n";
        // Say, this comes in handy with count() on an array that we want to use in an
        // SQL query such as 'WHERE foo IN (...)'
        $args = array('1', '2', '3');
        print implode(',', array_fill(0, count($args), '?'));
        print "\n";
        ?>
        Example Output:
        bar,bar,bar,bar,bar
        ?,?,?

        PHP str_replace() Function

        What does str_replace() do?

        The PHP str_replace() function will replace all occurrences of the search string with the replacement string.

        PHP str_replace() Syntax

         str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) : mixed

        PHP str_replace() Parameters

        1. search — The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.

        2. replace — The replacement value that replaces found search values. An array may be used to designate multiple replacements.

        3. subject — The string or array being searched and replaced on, otherwise known as the haystack.

        4. count — If passed, this will be set to the number of replacements performed.

        PHP str_replace() Return Value

        The PHP str_replace() function returns a string or an array with the replaced values.

        PHP str_replace() Working Examples

        1. Basic str_replace() examples

        <?php
        // Provides: <body text='black'>
        $bodytag = str_replace("%body%", "black", "<body text='%body%'>");
        // Provides: Hll Wrld f PHP
        $vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
        $onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
        // Provides: You should eat pizza, beer, and ice cream every day
        $phrase  = "You should eat fruits, vegetables, and fiber every day.";
        $healthy = array("fruits", "vegetables", "fiber");
        $yummy   = array("pizza", "beer", "ice cream");
        $newphrase = str_replace($healthy, $yummy, $phrase);
        // Provides: 2
        $str = str_replace("ll", "", "good golly miss molly!", $count);
        echo $count;
        ?>

        2. Examples of potential str_replace() gotchas

        <?php
        // Order of replacement
        $str     = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
        $order   = array("\r\n", "\n", "\r");
        $replace = '<br />';
        // Processes \r\n's first so they aren't converted twice.
        $newstr = str_replace($order, $replace, $str);
        // Outputs F because A is replaced with B, then B is replaced with C, and so on...
        // Finally E is replaced with F, because of left to right replacements.
        $search  = array('A', 'B', 'C', 'D', 'E');
        $replace = array('B', 'C', 'D', 'E', 'F');
        $subject = 'A';
        echo str_replace($search, $replace, $subject);
        // Outputs: apearpearle pear
        // For the same reason mentioned above
        $letters = array('a', 'p');
        $fruit   = array('apple', 'pear');
        $text    = 'a p';
        $output  = str_replace($letters, $fruit, $text);
        echo $output;
        ?>

        Important Points about PHP str_replace() Function

        1. Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.

        2. This function is case-sensitive. Use str_ireplace() for case-insensitive replace.

        Additional Tips from Fellow Developers

        Contributed By: nikolaz dot tang

        A faster way to replace the strings in multidimensional array is to json_encode() it, do the str_replace() and then json_decode() it, like this: 
         
        <?php 
        function str_replace_json($search, $replace, $subject){ 
             return json_decode(str_replace($search, $replace,  json_encode($subject))); 
         
        } 
        ?> 
         
        This method is almost 3x faster (in 10000 runs.) than using recursive calling and looping method, and 10x simpler in coding. 
         
        Compared to: 
         
        <?php 
        function str_replace_deep($search, $replace, $subject) 
        { 
            if (is_array($subject)) 
            { 
                foreach($subject as &$oneSubject) 
                    $oneSubject = str_replace_deep($search, $replace, $oneSubject); 
                unset($oneSubject); 
                return $subject; 
            } else { 
                return str_replace($search, $replace, $subject); 
            } 
        } 
        ?>

        Contributed By: moostende

        Note that this does not replace strings that become part of replacement strings. This may be a problem when you want to remove multiple instances of the same repetative pattern, several times in a row. 
         
        If you want to remove all dashes but one from the string '-aaa----b-c-----d--e---f' resulting in '-aaa-b-c-d-e-f', you cannot use str_replace. Instead, use preg_replace: 
         
        <?php 
        $challenge = '-aaa----b-c-----d--e---f'; 
        echo str_replace('--', '-', $challenge).'<br>'; 
        echo preg_replace('/--+/', '-', $challenge).'<br>'; 
        ?> 
         
        This outputs the following: 
        -aaa--b-c---d-e--f 
        -aaa-b-c-d-e-f

        Contributed By: Wes Foster

        Feel free to optimize this using the while/for or anything else, but this is a bit of code that allows you to replace strings found in an associative array. 
         
        For example: 
        <?php 
        $replace = array( 
        'dog' => 'cat', 
        'apple' => 'orange' 
        'chevy' => 'ford' 
        ); 
         
        $string = 'I like to eat an apple with my dog in my chevy'; 
         
        echo str_replace_assoc($replace,$string); 
         
        // Echo: I like to eat an orange with my cat in my ford 
        ?> 
         
        Here is the function: 
         
        <?php 
        function strReplaceAssoc(array $replace, $subject) { 
           return str_replace(array_keys($replace), array_values($replace), $subject);    
        } 
        ?> 
         
        [Jun 1st, 2010 - EDIT BY thiago AT php DOT net: Function has been replaced with an updated version sent by ljelinek AT gmail DOT com]

        Contributed By: Alberto Lepe

        Be careful when replacing characters (or repeated patterns in the FROM and TO arrays): 
         
        For example: 
         
        <?php 
        $arrFrom = array("1","2","3","B"); 
        $arrTo = array("A","B","C","D"); 
        $word = "ZBB2"; 
        echo str_replace($arrFrom, $arrTo, $word); 
        ?> 
         
        I would expect as result: "ZDDB" 
        However, this return: "ZDDD" 
        (Because B = D according to our array) 
         
        To make this work, use "strtr" instead: 
         
        <?php 
        $arr = array("1" => "A","2" => "B","3" => "C","B" => "D"); 
        $word = "ZBB2"; 
        echo strtr($word,$arr); 
        ?> 
         
        This returns: "ZDDB"

        Contributed By: David Holt

        Be aware that if you use this for filtering & sanitizing some form of user input, or remove ALL instances of a string, there's another gotcha to watch out for:
        // Remove all double characters
        $string="1001011010";
        $string=str_replace(array("11","00"),"",$string);
        // Output: "110010"
        $string="<ht<html>ml> Malicious code </<html>html> etc";
        $string=str_replace(array("<html>","</html>"),"",$string);
        // Output: "<html> Malicious code </html> etc"

        Contributed By: jay_knows_(all)uk

        This strips out horrible MS word characters. 
        Just keep fine tuning it until you get what you need, you'll see ive commented some out which caused problems for me.
        There could be some that need adding in, but its a start to anyone who wishes to make their own custom function.
        <?php
        function msword_conversion($str) 
        { 
        $str = str_replace(chr(130), ',', $str);    // baseline single quote
        $str = str_replace(chr(131), 'NLG', $str);  // florin
        $str = str_replace(chr(132), '"', $str);    // baseline double quote
        $str = str_replace(chr(133), '...', $str);  // ellipsis
        $str = str_replace(chr(134), '**', $str);   // dagger (a second footnote)
        $str = str_replace(chr(135), '***', $str);  // double dagger (a third footnote)
        $str = str_replace(chr(136), '^', $str);    // circumflex accent
        $str = str_replace(chr(137), 'o/oo', $str); // permile
        $str = str_replace(chr(138), 'Sh', $str);   // S Hacek
        $str = str_replace(chr(139), '<', $str);    // left single guillemet
        // $str = str_replace(chr(140), 'OE', $str);   // OE ligature
        $str = str_replace(chr(145), "'", $str);    // left single quote
        $str = str_replace(chr(146), "'", $str);    // right single quote
        // $str = str_replace(chr(147), '"', $str);    // left double quote
        // $str = str_replace(chr(148), '"', $str);    // right double quote
        $str = str_replace(chr(149), '-', $str);    // bullet
        $str = str_replace(chr(150), '-–', $str);    // endash
        $str = str_replace(chr(151), '--', $str);   // emdash
        // $str = str_replace(chr(152), '~', $str);    // tilde accent
        // $str = str_replace(chr(153), '(TM)', $str); // trademark ligature
        $str = str_replace(chr(154), 'sh', $str);   // s Hacek
        $str = str_replace(chr(155), '>', $str);    // right single guillemet
        // $str = str_replace(chr(156), 'oe', $str);   // oe ligature
        $str = str_replace(chr(159), 'Y', $str);    // Y Dieresis
        $str = str_replace('°C', '&deg;C', $str);    // Celcius is used quite a lot so it makes sense to add this in
        $str = str_replace('£', '&pound;', $str); 
        $str = str_replace("'", "'", $str);
        $str = str_replace('"', '"', $str);
        $str = str_replace('–', '&ndash;', $str);
        return $str;
        }
        ?>

        PHP str_rot13() Function

        What does str_rot13() do?

        The PHP str_rot13() function will give you the resulting string.

        PHP str_rot13() Syntax

         str_rot13 ( string $str ) : string

        PHP str_rot13() Parameters

        1. str — The input string.

        PHP str_rot13() Return Value

        The PHP str_rot13() function returns the ROT13 version of the given string.

        PHP str_rot13() Working Examples

        1. str_rot13() example

        <?php
        echo str_rot13('PHP 4.3.0'); // CUC 4.3.0
        ?>

        Additional Tips from Fellow Developers

        Contributed By: shaun

        I was reminded again of the desire for a generic str_rot function. Character manipulation loops in PHP are slow compared to their C counterparts, so here's a tuned version of the previous function I posted. It's 1.6 times as fast, mainly by avoiding chr() calls.
        <?php
        function str_rot($s, $n = 13) {
            static $letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $n = (int)$n % 26;
            if (!$n) return $s;
            if ($n == 13) return str_rot13($s);
            for ($i = 0, $l = strlen($s); $i < $l; $i++) {
                $c = $s[$i];
                if ($c >= 'a' && $c <= 'z') {
                    $s[$i] = $letters[(ord($c) - 71 + $n) % 26];
                } else if ($c >= 'A' && $c <= 'Z') {
                    $s[$i] = $letters[(ord($c) - 39 + $n) % 26 + 26];
                }
            }
            return $s;
        }
        ?>
        But using strtr() you can get something 10 times as fast as the above :
        <?php
        function str_rot($s, $n = 13) {
            static $letters = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz';
            $n = (int)$n % 26;
            if (!$n) return $s;
            if ($n < 0) $n += 26;
            if ($n == 13) return str_rot13($s);
            $rep = substr($letters, $n * 2) . substr($letters, 0, $n * 2);
            return strtr($s, $letters, $rep);
        }
        ?>
        This technique is faster because PHP's strtr is implemented in C using a byte lookup table (it has O(m + n) complexity). However, PHP 6 will use Unicode, so I guess(?) strtr will then have to be implemented with a search for each character (O(m * n)). Using strtr might still be faster since it offloads the character manipulation to C rather than PHP, but I don't really know. Take your pick.
        Happy coding!
        (Benchmark code):
        <?php
        for ($k = 0; $k < 10; $k++) {
            $s = 'The quick brown fox jumps over the lazy dog.';
            $t = microtime(1);
            for ($i = 0; $i < 1000; $i++) $s = str_rot($s, $i);
            $t = microtime(1) - $t;
            echo number_format($t, 3) . "\n";
        }
        ?>

        PHP str_shuffle() Function

        What does str_shuffle() do?

        The PHP str_shuffle() function will str_shuffle() shuffles a string. One permutation of all possible is created.

        PHP str_shuffle() Syntax

         str_shuffle ( string $str ) : string

        PHP str_shuffle() Parameters

        1. str — The input string.

        PHP str_shuffle() Return Value

        The PHP str_shuffle() function returns the shuffled string.

        PHP str_shuffle() Working Examples

        1. str_shuffle() example

        <?php
        $str = 'abcdef';
        $shuffled = str_shuffle($str);
        // This will echo something like: bfdaec
        echo $shuffled;
        ?>

        Changelog for PHP str_shuffle() Function

        7.1.0 — The internal randomization algorithm has been changed to use the » Mersenne Twister Random Number Generator instead of the libc rand function.

        Important Points about PHP str_shuffle() Function

        1. This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead.

        Additional Tips from Fellow Developers

        Contributed By: jojersztajner

        Aoccdrnig to rseearch at an Elingsh uinervtisy, it deosn't mttaer in waht oredr the ltteers in a wrod are, the olny iprmoatnt tihng is that the frist and lsat ltteer is at the rghit pclae. The rset can be a toatl mses and you can sitll raed it wouthit a porbelm. Tihs is bcuseae we do not raed ervey lteter by it slef but the wrod as a wlohe.
        Hree's a cdoe taht slerbmcas txet in tihs way:
        <?php
            function scramble_word($word) {
                if (strlen($word) < 2)
                    return $word;
                else
                    return $word{0} . str_shuffle(substr($word, 1, -1)) . $word{strlen($word) - 1};
            }
            echo preg_replace('/(\w+)/e', 'scramble_word("\1")', 'A quick brown fox jumped over the lazy dog.');
        ?>
        It may be ufseul if you wnat to cetare an aessblicce CTCPAHA.

        Contributed By: blamoo2

        This function is affected by srand():
        <?php
        srand(12345);
        echo str_shuffle('Randomize me') . '<br/>'; // "demmiezr aon"
        echo str_shuffle('Randomize me') . '<br/>'; // "izadmeo rmen"
        srand(12345);
        echo str_shuffle('Randomize me') . '<br/>'; // "demmiezr aon" again
        ?>

        Contributed By:

        A proper unicode string shuffle;
        <?php
        function str_shuffle_unicode($str) {
            $tmp = preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
            shuffle($tmp);
            return join("", $tmp);
        }
        ?>
        $str = "Şeker yârim"; // My sweet love
        echo str_shuffle($str); // i�eymrŢekr �
        echo str_shuffle_unicode($str); // Şr mreyeikâ

        PHP str_split() Function

        What does str_split() do?

        The PHP str_split() function will converts a string to an array.

        PHP str_split() Syntax

         str_split ( string $string [, int $split_length = 1 ] ) : array

        PHP str_split() Parameters

        1. string — The input string.

        2. split_length — Maximum length of the chunk.

        PHP str_split() Return Value

        The PHP str_split() function returns d array will be broken down into chunks with each being split_length in length, otherwise each chunk will be one character in length.

        PHP str_split() Working Examples

        1. Example uses of str_split()

        <?php
        $str = "Hello Friend";
        $arr1 = str_split($str);
        $arr2 = str_split($str, 3);
        print_r($arr1);
        print_r($arr2);
        ?>

        Output of the above code:

        Array
        (
         [0] => H
         [1] => e
         [2] => l
         [3] => l
         [4] => o
         [5] =>
         [6] => F
         [7] => r
         [8] => i
         [9] => e
         [10] => n
         [11] => d
        )
        Array
        (
         [0] => Hel
         [1] => lo
         [2] => Fri
         [3] => end
        )

        Important Points about PHP str_split() Function

        1. str_split() will split into bytes, rather than characters when dealing with a multi-byte encoded string.

        Additional Tips from Fellow Developers

        Contributed By:

        A proper unicode string split;
        <?php
        function str_split_unicode($str, $l = 0) {
            if ($l > 0) {
                $ret = array();
                $len = mb_strlen($str, "UTF-8");
                for ($i = 0; $i < $len; $i += $l) {
                    $ret[] = mb_substr($str, $i, $l, "UTF-8");
                }
                return $ret;
            }
            return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
        }
        ?>
        $s = "Ilık süt"; // Mild milk
        print_r(str_split($s, 3));
        print_r(str_split_unicode($s, 3));
        Array
        (
            [0] => Il�
            [1] => �k 
            [2] => sü
            [3] => t
        )
        Array
        (
            [0] => Ilı
            [1] => k s
            [2] => üt
        )

        Contributed By:

        A new version of "str_split_unicode" prev.
        <?php
        function str_split_unicode($str, $length = 1) {
            $tmp = preg_split('~~u', $str, -1, PREG_SPLIT_NO_EMPTY);
            if ($length > 1) {
                $chunks = array_chunk($tmp, $length);
                foreach ($chunks as $i => $chunk) {
                    $chunks[$i] = join('', (array) $chunk);
                }
                $tmp = $chunks;
            }
            return $tmp;
        }
        ?>
        $s = 'Özgür Yazılım!'; // Open Source!
        print_r(str_split_unicode($s));
        print_r(str_split_unicode($s, 3));
        Array
        (
            [0] => Ö
            [1] => z
            [2] => g
            [3] => ü
            [4] => r
            [5] =>  
            [6] => Y
            [7] => a
            [8] => z
            [9] => ı
            [10] => l
            [11] => ı
            [12] => m
            [13] => !
        )
        Array
        (
            [0] => Özg
            [1] => ür 
            [2] => Yaz
            [3] => ılı
            [4] => m!
        )

        PHP str_word_count() Function

        What does str_word_count() do?

        The PHP str_word_count() function will give you

        PHP str_word_count() Syntax

         str_word_count ( string $string [, int $format = 0 [, string $charlist ]] ) : mixed

        PHP str_word_count() Parameters

        1. string — The string

        2. format — Specify the return value of this function. The current supported values are:

        3. charlist — A list of additional characters which will be considered as ‘word’

        PHP str_word_count() Return Value

        The PHP str_word_count() function returns an array or an integer, depending on the format chosen.

        PHP str_word_count() Working Examples

        1. A str_word_count() example

        <?php
        $str = "Hello fri3nd, you're
               looking          good today!";
        print_r(str_word_count($str, 1));
        print_r(str_word_count($str, 2));
        print_r(str_word_count($str, 1, 'àáãç3'));
        echo str_word_count($str);
        ?>

        Output of the above code:

        Array
        (
         [0] => Hello
         [1] => fri
         [2] => nd
         [3] => you're
         [4] => looking
         [5] => good
         [6] => today
        )
        Array
        (
         [0] => Hello
         [6] => fri
         [10] => nd
         [14] => you're
         [29] => looking
         [46] => good
         [51] => today
        )
        Array
        (
         [0] => Hello
         [1] => fri3nd
         [2] => you're
         [3] => looking
         [4] => good
         [5] => today
        )
        7

        Changelog for PHP str_word_count() Function

        5.1.0 — Added the charlist parameter

        Additional Tips from Fellow Developers

        Contributed By: cito

        <?php
        /***
         * This simple utf-8 word count function (it only counts) 
         * is a bit faster then the one with preg_match_all
         * about 10x slower then the built-in str_word_count
         * 
         * If you need the hyphen or other code points as word-characters
         * just put them into the [brackets] like [^\p{L}\p{N}\'\-]
         * If the pattern contains utf-8, utf8_encode() the pattern,
         * as it is expected to be valid utf-8 (using the u modifier).
         **/
        // Jonny 5's simple word splitter
        function str_word_count_utf8($str) {
          return count(preg_split('~[^\p{L}\p{N}\']+~u',$str));
        }
        ?>

        Contributed By: splogamurugan

        We can also specify a range of values for charlist. 
         
        <?php 
        $str = "Hello fri3nd, you're 
               looking          good today! 
               look1234ing"; 
        print_r(str_word_count($str, 1, '0..3')); 
        ?> 
         
        will give the result as 
         
        Array ( [0] => Hello [1] => fri3nd [2] => you're [3] => looking [4] => good [5] => today [6] => look123 [7] => ing )

        PHP strcasecmp() Function

        What does strcasecmp() do?

        The PHP strcasecmp() function will binary safe case-insensitive string comparison.

        PHP strcasecmp() Syntax

         strcasecmp ( string $str1 , string $str2 ) : int

        PHP strcasecmp() Parameters

        1. str1 — The first string

        2. str2 — The second string

        PHP strcasecmp() Return Value

        The PHP strcasecmp() function returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

        PHP strcasecmp() Working Examples

        1. strcasecmp() example

        <?php
        $var1 = "Hello";
        $var2 = "hello";
        if (strcasecmp($var1, $var2) == 0) {
            echo '$var1 is equal to $var2 in a case-insensitive string comparison';
        }
        ?>

        Additional Tips from Fellow Developers

        Contributed By: chris

        A simple multibyte-safe case-insensitive string comparison:
        <?php
        function mb_strcasecmp($str1, $str2, $encoding = null) {
            if (null === $encoding) { $encoding = mb_internal_encoding(); }
            return strcmp(mb_strtoupper($str1, $encoding), mb_strtoupper($str2, $encoding));
        }
        ?>
        Caveat: watch out for edge cases like "ß".

        Contributed By: Anonymous

        The sample above is only true on some platforms that only use a simple 'C' locale, where individual bytes are considered as complete characters that are converted to lowercase before being differentiated.
        Other locales (see LC_COLLATE and LC_ALL) use the difference of collation order of characters, where characters may be groups of bytes taken from the input strings, or simply return -1, 0, or 1 as the collation order is not simply defined by comparing individual characters but by more complex rules.
        Don't base your code on a specific non null value returned by strcmp() or strcasecmp(): it is not portable. Just consider the sign of the result and be sure to use the correct locale!

        PHP strchr() Function

        What does strchr() do?

        The PHP strchr() function will this function is an alias of: strstr().

        PHP strchr() Syntax

        PHP strchr() Parameters

          This function does not accept any parameters.

          PHP strcmp() Function

          What does strcmp() do?

          The PHP strcmp() function will note that this comparison is case sensitive.

          PHP strcmp() Syntax

           strcmp ( string $str1 , string $str2 ) : int

          PHP strcmp() Parameters

          1. str1 — The first string.

          2. str2 — The second string.

          PHP strcmp() Return Value

          The PHP strcmp() function returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

          PHP strcmp() Working Examples

          1. strcmp() example

          <?php
          $var1 = "Hello";
          $var2 = "hello";
          if (strcmp($var1, $var2) !== 0) {
              echo '$var1 is not equal to $var2 in a case sensitive string comparison';
          }
          ?>

          Additional Tips from Fellow Developers

          Contributed By: jendoj

          If you rely on strcmp for safe string comparisons, both parameters must be strings, the result is otherwise extremely unpredictable.
          For instance you may get an unexpected 0, or return values of NULL, -2, 2, 3 and -3.
          strcmp("5", 5) => 0
          strcmp("15", 0xf) => 0
          strcmp(61529519452809720693702583126814, 61529519452809720000000000000000) => 0
          strcmp(NULL, false) => 0
          strcmp(NULL, "") => 0
          strcmp(NULL, 0) => -1
          strcmp(false, -1) => -2
          strcmp("15", NULL) => 2
          strcmp(NULL, "foo") => -3
          strcmp("foo", NULL) => 3
          strcmp("foo", false) => 3
          strcmp("foo", 0) => 1
          strcmp("foo", 5) => 1
          strcmp("foo", array()) => NULL + PHP Warning
          strcmp("foo", new stdClass) => NULL + PHP Warning
          strcmp(function(){}, "") => NULL + PHP Warning

          Contributed By: lehal2

          I hope this will give you a clear idea how strcmp works internally. 
           
          <?php 
          $str1 = "b"; 
          echo ord($str1); //98 
          echo "<br/>"; 
          $str2 = "t"; 
          echo ord($str2); //116 
          echo "<br/>"; 
          echo ord($str1)-ord($str2);//-18 
          $str1 = "bear"; 
          $str2 = "tear"; 
          $str3 = ""; 
          echo "<pre>"; 
          echo strcmp($str1, $str2); // -18 
          echo "<br/>"; 
          echo strcmp($str2, $str1); //18 
          echo "<br/>"; 
          echo strcmp($str2, $str2); //0 
          echo "<br/>"; 
          echo strcmp($str2, $str3); //4 
          echo "<br/>"; 
          echo strcmp($str3, $str2); //-4 
          echo "<br/>"; 
          echo strcmp($str3, $str3); // 0 
          echo "</pre>"; 
          ?>

          Contributed By: Rob Wiesler

          One big caveat - strings retrieved from the backtick operation may be zero terminated (C-style), and therefore will not be equal to the non-zero terminated strings (roughly Pascal-style) normal in PHP. The workaround is to surround every `` pair or shell_exec() function with the trim() function. This is likely to be an issue with other functions that invoke shells; I haven't bothered to check.
          On Debian Lenny (and RHEL 5, with minor differences), I get this:
          ====PHP====
          <?php
          $sz = `pwd`;
          $ps = "/var/www";
          echo "Zero-terminated string:<br />sz = ".$sz."<br />str_split(sz) = "; print_r(str_split($sz));
          echo "<br /><br />";
          echo "Pascal-style string:<br />ps = ".$ps."<br />str_split(ps) = "; print_r(str_split($ps));
          echo "<br /><br />";
          echo "Normal results of comparison:<br />";
          echo "sz == ps = ".($sz == $ps ? "true" : "false")."<br />";
          echo "strcmp(sz,ps) = ".strcmp($sz,$ps);
          echo "<br /><br />";
          echo "Comparison with trim()'d zero-terminated string:<br />";
          echo "trim(sz) = ".trim($sz)."<br />";
          echo "str_split(trim(sz)) = "; print_r(str_split(trim($sz))); echo "<br />";
          echo "trim(sz) == ps = ".(trim($sz) == $ps ? "true" : "false")."<br />";
          echo "strcmp(trim(sz),ps) = ".strcmp(trim($sz),$ps);
          ?>
          ====Output====
          Zero-terminated string:
          sz = /var/www 
          str_split(sz) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w [8] => ) 
          Pascal-style string:
          ps = /var/www
          str_split(ps) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w ) 
          Normal results of comparison:
          sz == ps = false
          strcmp(sz,ps) = 1
          Comparison with trim()'d zero-terminated string:
          trim(sz) = /var/www
          str_split(trim(sz)) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w ) 
          trim(sz) == ps = true
          strcmp(trim(sz),ps) = 0

          Contributed By: frewuill

          Hey be sure the string you are comparing has not special characters like '\n' or something like that.

          PHP strcoll() Function

          What does strcoll() do?

          The PHP strcoll() function will note that this comparison is case sensitive, and unlike strcmp() this function is not binary safe.

          PHP strcoll() Syntax

           strcoll ( string $str1 , string $str2 ) : int

          PHP strcoll() Parameters

          1. str1 — The first string.

          2. str2 — The second string.

          PHP strcoll() Return Value

          The PHP strcoll() function returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

          PHP strcspn() Function

          What does strcspn() do?

          The PHP strcspn() function will find length of initial segment not matching mask.

          PHP strcspn() Syntax

           strcspn ( string $subject , string $mask [, int $start [, int $length ]] ) : int

          PHP strcspn() Parameters

          1. subject — The string to examine.

          2. mask — The string containing every disallowed character.

          3. start — The position in subject to start searching.

          4. length — The length of the segment from subject to examine.

          PHP strcspn() Return Value

          The PHP strcspn() function returns the length of the initial segment of subject which consists entirely of characters not in mask.

          PHP strcspn() Working Examples

          1. strcspn() example

          <?php
          $a = strcspn('abcd',  'apple');
          $b = strcspn('abcd',  'banana');
          $c = strcspn('hello', 'l');
          $d = strcspn('hello', 'world');
          $e = strcspn('abcdhelloabcd', 'abcd', -9);
          $f = strcspn('abcdhelloabcd', 'abcd', -9, -5);
          var_dump($a);
          var_dump($b);
          var_dump($c);
          var_dump($d);
          var_dump($e);
          var_dump($f);
          ?>

          Output of the above code:

          int(0)
          int(0)
          int(2)
          int(2)
          int(5)
          int(4)

          Important Points about PHP strcspn() Function

          1. When a start parameter is set, the returned length is counted starting from this position, not from the beginning of subject.

          PHP strip_tags() Function

          What does strip_tags() do?

          The PHP strip_tags() function will give you a string with all NULL bytes, HTML and PHP tags stripped from a given str. It uses the same tag stripping state machine as the fgetss() function.

          PHP strip_tags() Syntax

           strip_tags ( string $str [, string $allowable_tags ] ) : string

          PHP strip_tags() Parameters

          1. str — The input string.

          2. allowable_tags — You can use the optional second parameter to specify tags which should not be stripped.

          PHP strip_tags() Return Value

          The PHP strip_tags() function returns the stripped string.

          PHP strip_tags() Working Examples

          1. strip_tags() example

          <?php
          $text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
          echo strip_tags($text);
          echo "\n";
          // Allow <p> and <a>
          echo strip_tags($text, '<p><a>');
          ?>

          Output of the above code:

          Test paragraph. Other text
          <p>Test paragraph.</p> <a href="#fragment">Other text</a>

          Changelog for PHP strip_tags() Function

          5.3.4 — strip_tags() ignores self-closing XHTML tags in allowable_tags.

          Important Points about PHP strip_tags() Function

          1. HTML comments and PHP tags are also stripped. This is hardcoded and can not be changed with allowable_tags.

          2. In PHP 5.3.4 and later, self-closing XHTML tags are ignored and only non-self-closing tags should be used in allowable_tags. For example, to allow both <br> and <br/>, you should use:

          3. <?php
            strip_tags($input, '<br>');
            ?>
          4. This function should not be used to try to prevent XSS attacks. Use more appropiate functions like htmlspecialchars() or other means depending on the context of the output.

          5. Because strip_tags() does not actually validate the HTML, partial or broken tags can result in the removal of more text/data than expected.

          6. This function does not modify any attributes on the tags that you allow using allowable_tags, including the style and onmouseover attributes that a mischievous user may abuse when posting text that will be shown to other users.

          7. Tag names within the input HTML that are greater than 1023 bytes in length will be treated as though they are invalid, regardless of the allowable_tags parameter.

          Additional Tips from Fellow Developers

          Contributed By: mariusz.tarnaski

          Hi. I made a function that removes the HTML tags along with their contents: 
           
          Function: 
          <?php 
          function strip_tags_content($text, $tags = '', $invert = FALSE) { 
           
            preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags); 
            $tags = array_unique($tags[1]); 
              
            if(is_array($tags) AND count($tags) > 0) { 
              if($invert == FALSE) { 
                return preg_replace('@<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>@si', '', $text); 
              } 
              else { 
                return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?</\1>@si', '', $text); 
              } 
            } 
            elseif($invert == FALSE) { 
              return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text); 
            } 
            return $text; 
          } 
          ?> 
           
          Sample text: 
          $text = '<b>sample</b> text with <div>tags</div>'; 
           
          Result for strip_tags($text): 
          sample text with tags 
           
          Result for strip_tags_content($text): 
           text with 
           
          Result for strip_tags_content($text, '<b>'): 
          <b>sample</b> text with 
           
          Result for strip_tags_content($text, '<b>', TRUE); 
           text with <div>tags</div> 
           
          I hope that someone is useful :)

          Contributed By: doug

          "5.3.4    strip_tags() no longer strips self-closing XHTML tags unless the self-closing XHTML tag is also given in allowable_tags."
          This is poorly worded.
          The above seems to be saying that, since 5.3.4, if you don't specify "<br/>" in allowable_tags then "<br/>" will not be stripped... but that's not actually what they're trying to say.
          What it means is, in versions prior to 5.3.4, it "strips self-closing XHTML tags unless the self-closing XHTML tag is also given in allowable_tags", and that since 5.3.4 this is no longer the case.
          So what reads as "no longer strips self-closing tags (unless the self-closing XHTML tag is also given in allowable_tags)" is actually saying "no longer (strips self-closing tags unless the self-closing XHTML tag is also given in allowable_tags)".
          i.e.
          pre-5.3.4: strip_tags('Hello World<br><br/>','<br>') => 'Hello World<br>' // strips <br/> because it wasn't explicitly specified in allowable_tags
          5.3.4 and later: strip_tags('Hello World<br><br/>','<br>') => 'Hello World<br><br/>' // does not strip <br/> because PHP matches it with <br> in allowable_tags

          Contributed By: stever

          Since strip_tags does not remove attributes and thus creates a potential XSS security hole, here is a small function I wrote to allow only specific tags with specific attributes and strip all other tags and attributes.
          If you only allow formatting tags such as b, i, and p, and styling attributes such as class, id and style, this will strip all javascript including event triggers in formatting tags.
          Note that allowing anchor tags or href attributes opens another potential security hole that this solution won't protect against. You'll need more comprehensive protection if you plan to allow links in your text.
          <?php
          function stripUnwantedTagsAndAttrs($html_str){
            $xml = new DOMDocument();
          //Suppress warnings: proper error handling is beyond scope of example
            libxml_use_internal_errors(true);
          //List the tags you want to allow here, NOTE you MUST allow html and body otherwise entire string will be cleared
            $allowed_tags = array("html", "body", "b", "br", "em", "hr", "i", "li", "ol", "p", "s", "span", "table", "tr", "td", "u", "ul");
          //List the attributes you want to allow here
            $allowed_attrs = array ("class", "id", "style");
            if (!strlen($html_str)){return false;}
            if ($xml->loadHTML($html_str, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD)){
              foreach ($xml->getElementsByTagName("*") as $tag){
                if (!in_array($tag->tagName, $allowed_tags)){
                  $tag->parentNode->removeChild($tag);
                }else{
                  foreach ($tag->attributes as $attr){
                    if (!in_array($attr->nodeName, $allowed_attrs)){
                      $tag->removeAttribute($attr->nodeName);
                    }
                  }
                }
              }
            }
            return $xml->saveHTML();
          }
          ?>

          Contributed By: bzplan

          A HTML code like this: 
          <?php
          $html = '
          <div>
          <p style="color:blue;">color is blue</p><p>size is <span style="font-size:200%;">huge</span></p>
          <p>material is wood</p>
          </div>
          '; 
          ?>
          with <?php $str = strip_tags($html); ?>
          ... the result is:
          $str = 'color is bluesize is huge
          material is wood'; 
          notice: the words 'blue' and 'size' grow together :( 
          and line-breaks are still in new string $str
          if you need a space between the words (and without line-break) 
          use my function: <?php $str = rip_tags($html); ?>
          ... the result is:
          $str = 'color is blue size is huge material is wood'; 
          the function: 
          <?php
          // -------------------------------------------------------------- 
          function rip_tags($string) { 
              
              // ----- remove HTML TAGs ----- 
              $string = preg_replace ('/<[^>]*>/', ' ', $string); 
              
              // ----- remove control characters ----- 
              $string = str_replace("\r", '', $string);    // --- replace with empty space
              $string = str_replace("\n", ' ', $string);   // --- replace with space
              $string = str_replace("\t", ' ', $string);   // --- replace with space
              
              // ----- remove multiple spaces ----- 
              $string = trim(preg_replace('/ {2,}/', ' ', $string));
              
              return $string; 
          }
          // -------------------------------------------------------------- 
          ?>
          the KEY is the regex pattern: '/<[^>]*>/'
          instead of strip_tags() 
          ... then remove control characters and multiple spaces
          :)

          Contributed By: CEO

          Note the different outputs from different versions of the same tag: 
           
          <?php // striptags.php 
          $data = '<br>Each<br/>New<br />Line'; 
          $new  = strip_tags($data, '<br>'); 
          var_dump($new);  // OUTPUTS string(21) "<br>EachNew<br />Line" 
           
          <?php // striptags.php 
          $data = '<br>Each<br/>New<br />Line'; 
          $new  = strip_tags($data, '<br/>'); 
          var_dump($new); // OUTPUTS string(16) "Each<br/>NewLine" 
           
          <?php // striptags.php 
          $data = '<br>Each<br/>New<br />Line'; 
          $new  = strip_tags($data, '<br />'); 
          var_dump($new); // OUTPUTS string(11) "EachNewLine" 
          ?>

          Contributed By:

          Features:
          * allowable tags (as in strip_tags),
          * optional stripping attributes of the allowable tags,
          * optional comment preserving,
          * deleting broken and unclosed tags and comments,
          * optional callback function call for every piece processed allowing for flexible replacements.
          <?php
          function better_strip_tags( $str, $allowable_tags = '', $strip_attrs = false, $preserve_comments = false, callable $callback = null ) {
            $allowable_tags = array_map( 'strtolower', array_filter( // lowercase
                preg_split( '/(?:>|^)\\s*(?:<|$)/', $allowable_tags, -1, PREG_SPLIT_NO_EMPTY ), // get tag names
                function( $tag ) { return preg_match( '/^[a-z][a-z0-9_]*$/i', $tag ); } // filter broken
            ) );
            $comments_and_stuff = preg_split( '/(<!--.*?(?:-->|$))/', $str, -1, PREG_SPLIT_DELIM_CAPTURE );
            foreach ( $comments_and_stuff as $i => $comment_or_stuff ) {
              if ( $i % 2 ) { // html comment
                if ( !( $preserve_comments && preg_match( '/<!--.*?-->/', $comment_or_stuff ) ) ) {
                  $comments_and_stuff[$i] = '';
                }
              } else { // stuff between comments
                $tags_and_text = preg_split( "/(<(?:[^>\"']++|\"[^\"]*+(?:\"|$)|'[^']*+(?:'|$))*(?:>|$))/", $comment_or_stuff, -1, PREG_SPLIT_DELIM_CAPTURE );
                foreach ( $tags_and_text as $j => $tag_or_text ) {
                  $is_broken = false;
                  $is_allowable = true;
                  $result = $tag_or_text;
                  if ( $j % 2 ) { // tag
                    if ( preg_match( "%^(</?)([a-z][a-z0-9_]*)\\b(?:[^>\"'/]++|/+?|\"[^\"]*\"|'[^']*')*?(/?>)%i", $tag_or_text, $matches ) ) {
                      $tag = strtolower( $matches[2] );
                      if ( in_array( $tag, $allowable_tags ) ) {
                        if ( $strip_attrs ) {
                          $opening = $matches[1];
                          $closing = ( $opening === '</' ) ? '>' : $closing;
                          $result = $opening . $tag . $closing;
                        }
                      } else {
                        $is_allowable = false;
                        $result = '';
                      }
                    } else {
                      $is_broken = true;
                      $result = '';
                    }
                  } else { // text
                    $tag = false;
                  }
                  if ( !$is_broken && isset( $callback ) ) {
                    // allow result modification
                    call_user_func_array( $callback, array( &$result, $tag_or_text, $tag, $is_allowable ) );
                  }
                  $tags_and_text[$j] = $result;
                }
                $comments_and_stuff[$i] = implode( '', $tags_and_text );
              }
            }
            $str = implode( '', $comments_and_stuff );
            return $str;
          }
          ?>
          Callback arguments:
          * &$result: contains text to be placed insted of original piece (e.g. empty string for forbidden tags), it can be changed;
          * $tag_or_text: original piece of text or a tag (see below);
          * $tag: false for text between tags, lowercase tag name for tags;
          * $is_allowable: boolean telling if a tag isn't allowed (to avoid double checking), always true for text between tags
          Callback function isn't called for comments and broken tags.
          Caution: the function doesn't fully validate tags (the more so HTML itself), it just force strips those obviously broken (in addition to stripping forbidden tags). If you want to get valid tags then use strip_attrs option, though it doesn't guarantee tags are balanced or used in the appropriate context. For complex logic consider using DOM parser.

          PHP stripcslashes() Function

          What does stripcslashes() do?

          The PHP stripcslashes() function will un-quote string quoted with addcslashes().

          PHP stripcslashes() Syntax

           stripcslashes ( string $str ) : string

          PHP stripcslashes() Parameters

          1. str — The string to be unescaped.

          PHP stripcslashes() Return Value

          The PHP stripcslashes() function returns the unescaped string.

          PHP stripos() Function

          What does stripos() do?

          The PHP stripos() function will find the position of the first occurrence of a case-insensitive substring in a string.

          PHP stripos() Syntax

           stripos ( string $haystack , mixed $needle [, int $offset = 0 ] ) : int

          PHP stripos() Parameters

          1. haystack — The string to search in.

          2. needle — Note that the needle may be a string of one or more characters.

          3. offset — If specified, search will start this number of characters counted from the beginning of the string. If the offset is negative, the search will start this number of characters counted from the end of the string.

          PHP stripos() Return Value

          The PHP stripos() function returns the position of where the needle exists relative to the beginnning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.

          PHP stripos() Working Examples

          1. stripos() examples

          <?php
          $findme    = 'a';
          $mystring1 = 'xyz';
          $mystring2 = 'ABC';
          $pos1 = stripos($mystring1, $findme);
          $pos2 = stripos($mystring2, $findme);
          // Nope, 'a' is certainly not in 'xyz'
          if ($pos1 === false) {
              echo "The string '$findme' was not found in the string '$mystring1'";
          }
          // Note our use of ===.  Simply == would not work as expected
          // because the position of 'a' is the 0th (first) character.
          if ($pos2 !== false) {
              echo "We found '$findme' in '$mystring2' at position $pos2";
          }
          ?>

          Changelog for PHP stripos() Function

          7.1.0 — Support for negative offsets has been added.

          Important Points about PHP stripos() Function

          1. This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

          Additional Tips from Fellow Developers

          Contributed By: emperorshishire

          I found myself needing to find the first position of multiple needles in one haystack.  So I wrote this little function:
          <?php
          function multineedle_stripos($haystack, $needles, $offset=0) {
              foreach($needles as $needle) {
                  $found[$needle] = stripos($haystack, $needle, $offset);
              }
              return $found;
          }
          // It works as such:
          $haystack = "The quick brown fox jumps over the lazy dog.";
          $needle = array("fox", "dog", ".", "duck")
          var_dump(multineedle_stripos($haystack, $needle));
          /* Output:
             array(3) {
               ["fox"]=>
               int(16)
               ["dog"]=>
               int(40)
               ["."]=>
               int(43)
               ["duck"]=>
               bool(false)
             }
          */
          ?>

          PHP stripslashes() Function

          What does stripslashes() do?

          The PHP stripslashes() function will un-quotes a quoted string.

          PHP stripslashes() Syntax

           stripslashes ( string $str ) : string

          PHP stripslashes() Parameters

          1. str — The input string.

          PHP stripslashes() Return Value

          The PHP stripslashes() function returns a string with backslashes stripped off. (\’ becomes and so on.) Double backslashes (\\) are made into a single backslash (\).

          PHP stripslashes() Working Examples

          1. A stripslashes() example

          <?php
          $str = "Is your name O\'reilly?";
          // Outputs: Is your name O'reilly?
          echo stripslashes($str);
          ?>

          2. Using stripslashes() on an array

          <?php
          function stripslashes_deep($value)
          {
              $value = is_array($value) ?
                          array_map('stripslashes_deep', $value) :
                          stripslashes($value);
              return $value;
          }
          // Example
          $array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
          $array = stripslashes_deep($array);
          // Output
          print_r($array);
          ?>

          Output of the above code:

          Array
          (
           [0] => f'oo
           [1] => b'ar
           [2] => Array
           (
           [0] => fo'o
           [1] => b'ar
           )
          )

          Important Points about PHP stripslashes() Function

          1. If magic_quotes_sybase is on, no backslashes are stripped off but two apostrophes are replaced by one instead.

          2. stripslashes() is not recursive. If you want to apply this function to a multi-dimensional array, you need to use a recursive function.

          Additional Tips from Fellow Developers

          Contributed By: ivijan dot stefan

          Sometimes for some reason is happens that PHP or Javascript or some naughty insert a lot of  backslash. Ordinary function does not notice that. Therefore, it is necessary that the bit "inflate":
          <?php
          function removeslashes($string)
          {
              $string=implode("",explode("\\",$string));
              return stripslashes(trim($string));
          }
          /* Example */
          $text="My dog don\\\\\\\\\\\\\\\\'t like the postman!";
          echo removeslashes($text);
          ?>
          RESULT: My dog don't like the postman!
          This flick has served me wery well, because I had this problem before.

          PHP stristr() Function

          What does stristr() do?

          The PHP stristr() function will give you all of haystack starting from and including the first occurrence of needle to the end.

          PHP stristr() Syntax

           stristr ( string $haystack , mixed $needle [, bool $before_needle = FALSE ] ) : string

          PHP stristr() Parameters

          1. haystack — The string to search in

          2. needle — If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

          3. before_needle — If TRUE, stristr() returns the part of the haystack before the first occurrence of the needle (excluding needle).

          PHP stristr() Return Value

          The PHP stristr() function returns the matched substring. If needle is not found, return FALSE.

          PHP stristr() Working Examples

          1. stristr() example

          <?php
            $email = 'USER@EXAMPLE.com';
            echo stristr($email, 'e'); // outputs ER@EXAMPLE.com
            echo stristr($email, 'e', true); // As of PHP 5.3.0, outputs US
          ?>

          2. Testing if a string is found or not

          <?php
            $string = 'Hello World!';
            if(stristr($string, 'earth') === FALSE) {
              echo '"earth" not found in string';
            }
          // outputs: "earth" not found in string
          ?>

          3. Using a non “string” needle

          <?php
            $string = 'APPLE';
            echo stristr($string, 97); // 97 = lowercase a
          // outputs: APPLE
          ?>

          Changelog for PHP stristr() Function

          5.3.0 — Added the optional parameter before_needle.

          Additional Tips from Fellow Developers

          Contributed By:

          There was a change in PHP 4.2.3 that can cause a warning message
          to be generated when using stristr(), even though no message was
          generated in older versions of PHP.
          The following will generate a warning message in 4.0.6 and 4.2.3:
            stristr("haystack", "");
               OR
            $needle = "";  stristr("haystack", $needle);
          This will _not_ generate an "Empty Delimiter" warning message in
          4.0.6, but _will_ in 4.2.3:
            unset($needle); stristr("haystack", $needle);
          Here's a URL that documents what was changed:
          http://groups.google.ca/groups?selm=cvshholzgra1031224321%40cvsserver

          PHP strlen() Function

          What does strlen() do?

          The PHP strlen() function will give you the length of the given string.

          PHP strlen() Syntax

           strlen ( string $string ) : int

          PHP strlen() Parameters

          1. string — The string being measured for length.

          PHP strlen() Return Value

          The PHP strlen() function returns the length of the string on success, and 0 if the string is empty.

          PHP strlen() Working Examples

          1. A strlen() example

          <?php
          $str = 'abcdef';
          echo strlen($str); // 6
          $str = ' ab cd ';
          echo strlen($str); // 7
          ?>

          Changelog for PHP strlen() Function

          5.3.0 — Prior versions treated arrays as the string Array, thus returning a string length of 5 and emitting an E_NOTICE level error.

          Important Points about PHP strlen() Function

          1. strlen() returns the number of bytes rather than the number of characters in a string.

          2. strlen() returns NULL when executed on arrays, and an E_WARNING level error is emitted.

          Additional Tips from Fellow Developers

          Contributed By: rm dot nasir

          I want to share something seriously important for newbies or beginners of PHP who plays with strings of UTF8 encoded characters or the languages like: Arabic, Persian, Pashto, Dari, Chinese (simplified), Chinese (traditional), Japanese, Vietnamese, Urdu, Macedonian, Lithuanian, and etc.
          As the manual says: "strlen() returns the number of bytes rather than the number of characters in a string.", so if you want to get the number of characters in a string of UTF8 so use mb_strlen() instead of strlen().
          Example:
          <?php
          // the Arabic (Hello) string below is: 59 bytes and 32 characters
          $utf8 = "السلام علیکم ورحمة الله وبرکاته!";
          var_export( strlen($utf8) ); // 59
          echo "<br>";
          var_export( mb_strlen($utf8, 'utf8') ); // 32
          ?>

          Contributed By: chernyshevsky

          The easiest way to determine the character count of a UTF8 string is to pass the text through utf8_decode() first: 
           
          <?php 
          $length = strlen(utf8_decode($s)); 
          ?> 
           
          utf8_decode() converts characters that are not in ISO-8859-1 to '?', which, for the purpose of counting, is quite alright.

          Contributed By: basil

          We just ran into what we thought was a bug but turned out to be a documented difference in behavior between PHP 5.2 & 5.3.  Take the following code example:
          <?php
          $attributes = array('one', 'two', 'three');
          if (strlen($attributes) == 0 && !is_bool($attributes)) {
              echo "We are in the 'if'\n";  //  PHP 5.3
          } else {
              echo "We are in the 'else'\n";  //  PHP 5.2
          }
          ?>
          This is because in 5.2 strlen will automatically cast anything passed to it as a string, and casting an array to a string yields the string "Array".  In 5.3, this changed, as noted in the following point in the backward incompatible changes in 5.3 (http://www.php.net/manual/en/migration53.incompatible.php):
          "The newer internal parameter parsing API has been applied across all the extensions bundled with PHP 5.3.x. This parameter parsing API causes functions to return NULL when passed incompatible parameters. There are some exceptions to this rule, such as the get_class() function, which will continue to return FALSE on error."
          So, in PHP 5.3, strlen($attributes) returns NULL, while in PHP 5.2, strlen($attributes) returns the integer 5.  This likely affects other functions, so if you are getting different behaviors or new bugs suddenly, check if you have upgraded to 5.3 (which we did recently), and then check for some warnings in your logs like this:
          strlen() expects parameter 1 to be string, array given in /var/www/sis/lib/functions/advanced_search_lib.php on line 1028
          If so, then you are likely experiencing this changed behavior.

          Contributed By: vcardillo

          I would like to demonstrate that you need more than just this function in order to truly test for an empty string. The reason being that <?php strlen(null); ?> will return 0. So how do you know if the value was null, or truly an empty string?
          <?php
          $foo = null;
          $len = strlen(null);
          $bar = '';
          echo "Length: " . strlen($foo) . "<br>";
          echo "Length: $len <br>";
          echo "Length: " . strlen(null) . "<br>";
          if (strlen($foo) === 0) echo 'Null length is Zero <br>';
          if ($len === 0) echo 'Null length is still Zero <br>';
          if (strlen($foo) == 0 && !is_null($foo)) echo '!is_null(): $foo is truly an empty string <br>';
          else echo '!is_null(): $foo is probably null <br>';
          if (strlen($foo) == 0 && isset($foo)) echo 'isset(): $foo is truly an empty string <br>';
          else echo 'isset(): $foo is probably null <br>';
          if (strlen($bar) == 0 && !is_null($bar)) echo '!is_null(): $bar is truly an empty string <br>';
          else echo '!is_null(): $foo is probably null <br>';
          if (strlen($bar) == 0 && isset($bar)) echo 'isset(): $bar is truly an empty string <br>';
          else echo 'isset(): $foo is probably null <br>';
          ?>
          // Begin Output:
          Length: 0
          Length: 0 
          Length: 0
          Null length is Zero 
          Null length is still Zero 
          !is_null(): $foo is probably null 
          isset(): $foo is probably null 
          !is_null(): $bar is truly an empty string 
          isset(): $bar is truly an empty string 
          // End Output
          So it would seem you need either is_null() or isset() in addition to strlen() if you care whether or not the original value was null.

          Contributed By: jasonrohrer

          PHP's strlen function behaves differently than the C strlen function in terms of its handling of null bytes ('\0').  
          In PHP, a null byte in a string does NOT count as the end of the string, and any null bytes are included in the length of the string.
          For example, in PHP:
          strlen( "te\0st" ) = 5
          In C, the same call would return 2.
          Thus, PHP's strlen function can be used to find the number of bytes in a binary string (for example, binary data returned by base64_decode).

          Contributed By: tux

          Attention with utf8:
          $foo = "bär";
          strlen($foo) will return 4 and not 3 as expected..

          PHP strnatcasecmp() Function

          What does strnatcasecmp() do?

          The PHP strnatcasecmp() function will case insensitive string comparisons using a “natural order” algorithm.

          PHP strnatcasecmp() Syntax

           strnatcasecmp ( string $str1 , string $str2 ) : int

          PHP strnatcasecmp() Parameters

          1. str1 — The first string.

          2. str2 — The second string.

          PHP strnatcasecmp() Return Value

          The PHP strnatcasecmp() function returns < 0 if str1 is less than str2 > 0 if str1 is greater than str2, and 0 if they are equal.

          PHP strnatcmp() Function

          What does strnatcmp() do?

          The PHP strnatcmp() function will string comparisons using a “natural order” algorithm.

          PHP strnatcmp() Syntax

           strnatcmp ( string $str1 , string $str2 ) : int

          PHP strnatcmp() Parameters

          1. str1 — The first string.

          2. str2 — The second string.

          PHP strnatcmp() Return Value

          The PHP strnatcmp() function returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

          PHP strncasecmp() Function

          What does strncasecmp() do?

          The PHP strncasecmp() function will binary safe case-insensitive string comparison of the first n characters.

          PHP strncasecmp() Syntax

           strncasecmp ( string $str1 , string $str2 , int $len ) : int

          PHP strncasecmp() Parameters

          1. str1 — The first string.

          2. str2 — The second string.

          3. len — The length of strings to be used in the comparison.

          PHP strncasecmp() Return Value

          The PHP strncasecmp() function returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

          PHP strncmp() Function

          What does strncmp() do?

          The PHP strncmp() function will binary safe string comparison of the first n characters.

          PHP strncmp() Syntax

           strncmp ( string $str1 , string $str2 , int $len ) : int

          PHP strncmp() Parameters

          1. str1 — The first string.

          2. str2 — The second string.

          3. len — Number of characters to use in the comparison.

          PHP strncmp() Return Value

          The PHP strncmp() function returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

          PHP strpbrk() Function

          What does strpbrk() do?

          The PHP strpbrk() function will search a string for any of a set of characters.

          PHP strpbrk() Syntax

           strpbrk ( string $haystack , string $char_list ) : string

          PHP strpbrk() Parameters

          1. haystack — The string where char_list is looked for.

          2. char_list — This parameter is case sensitive.

          PHP strpbrk() Return Value

          The PHP strpbrk() function returns a string starting from the character found, or FALSE if it is not found.

          PHP strpbrk() Working Examples

          1. strpbrk() example

          <?php
          $text = 'This is a Simple text.';
          // this echoes "is is a Simple text." because 'i' is matched first
          echo strpbrk($text, 'mi');
          // this echoes "Simple text." because chars are case sensitive
          echo strpbrk($text, 'S');
          ?>

          Additional Tips from Fellow Developers

          Contributed By: devnuhl

          If you're not looking to duplicate the rest of the string, but instead just want the offset, in the spirit of the str*pos() functions, use strcspn()

          PHP strpos() Function

          What does strpos() do?

          The PHP strpos() function will find the position of the first occurrence of a substring in a string.

          PHP strpos() Syntax

           strpos ( string $haystack , mixed $needle [, int $offset = 0 ] ) : int

          PHP strpos() Parameters

          1. haystack — The string to search in.

          2. needle — If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

          3. offset — If specified, search will start this number of characters counted from the beginning of the string. If the offset is negative, the search will start this number of characters counted from the end of the string.

          PHP strpos() Return Value

          The PHP strpos() function returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.

          PHP strpos() Working Examples

          1. Using ===

          <?php
          $mystring = 'abc';
          $findme   = 'a';
          $pos = strpos($mystring, $findme);
          // Note our use of ===.  Simply == would not work as expected
          // because the position of 'a' was the 0th (first) character.
          if ($pos === false) {
              echo "The string '$findme' was not found in the string '$mystring'";
          } else {
              echo "The string '$findme' was found in the string '$mystring'";
              echo " and exists at position $pos";
          }
          ?>

          2. Using !==

          <?php
          $mystring = 'abc';
          $findme   = 'a';
          $pos = strpos($mystring, $findme);
          // The !== operator can also be used.  Using != would not work as expected
          // because the position of 'a' is 0. The statement (0 != false) evaluates 
          // to false.
          if ($pos !== false) {
               echo "The string '$findme' was found in the string '$mystring'";
                   echo " and exists at position $pos";
          } else {
               echo "The string '$findme' was not found in the string '$mystring'";
          }
          ?>

          3. Using an offset

          <?php
          // We can search for the character, ignoring anything before the offset
          $newstring = 'abcdef abcdef';
          $pos = strpos($newstring, 'a', 1); // $pos = 7, not 0
          ?>

          Changelog for PHP strpos() Function

          7.1.0 — Support for negative offsets has been added.

          Important Points about PHP strpos() Function

          1. This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

          Additional Tips from Fellow Developers

          Contributed By: Suggested re-write for pink WARNING box

          WARNING
          As strpos may return either FALSE (substring absent) or 0 (substring at start of string), strict versus loose equivalency operators must be used very carefully.
          To know that a substring is absent, you must use:  
          === FALSE
          To know that a substring is present (in any position including 0), you can use either of:
          !== FALSE  (recommended)
           > -1  (note: or greater than any negative number)
          To know that a substring is at the start of the string, you must use:  
          === 0
          To know that a substring is in any position other than the start, you can use any of: 
           > 0  (recommended)
          != 0  (note: but not !== 0 which also equates to FALSE)
          != FALSE  (disrecommended as highly confusing)
          Also note that you cannot compare a value of "" to the returned value of strpos. With a loose equivalence operator (== or !=) it will return results which don't distinguish between the substring's presence versus position. With a strict equivalence operator (=== or !==) it will always return false.

          Contributed By: martijn

          This is a function I wrote to find all occurrences of a string, using strpos recursively.
          <?php
          function strpos_recursive($haystack, $needle, $offset = 0, &$results = array()) {                
              $offset = strpos($haystack, $needle, $offset);
              if($offset === false) {
                  return $results;            
              } else {
                  $results[] = $offset;
                  return strpos_recursive($haystack, $needle, ($offset + 1), $results);
              }
          }
          ?>
          This is how you use it:
          <?php
          $string = 'This is some string';
          $search = 'a';
          $found = strpos_recursive($string, $search);
          if($found) {
              foreach($found as $pos) {
                  echo 'Found "'.$search.'" in string "'.$string.'" at position <b>'.$pos.'</b><br />';
              }    
          } else {
              echo '"'.$search.'" not found in "'.$string.'"';
          }
          ?>

          Contributed By: fabio

          It is interesting to be aware of the behavior when the treatment of strings with characters using different encodings.
          <?php
          # Works like expected. There is no accent
          var_dump(strpos("Fabio", 'b'));
          #int(2)
          # The "á" letter is occupying two positions
          var_dump(strpos("Fábio", 'b')) ;
          #int(3)
          # Now, encoding the string "Fábio" to utf8, we get some "unexpected" outputs. Every letter that is no in regular ASCII table, will use 4 positions(bytes). The starting point remains like before.
          # We cant find the characted, because the haystack string is now encoded.
          var_dump(strpos(utf8_encode("Fábio"), 'á'));
          #bool(false)
          # To get the expected result, we need to encode the needle too
          var_dump(strpos(utf8_encode("Fábio"), utf8_encode('á')));
          #int(1) 
          # And, like said before, "á" occupies 4 positions(bytes)
          var_dump(strpos(utf8_encode("Fábio"), 'b'));
          #int(5)

          Contributed By: mtroy dot student

          When you want to know how much of substring occurrences, you'll use "substr_count".
          But, retrieve their positions, will be harder.
          So, you can do it by starting with the last occurrence :
          function strpos_r($haystack, $needle)
          {
              if(strlen($needle) > strlen($haystack))
                  trigger_error(sprintf("%s: length of argument 2 must be <= argument 1", __FUNCTION__), E_USER_WARNING);
              $seeks = array();
              while($seek = strrpos($haystack, $needle))
              {
                  array_push($seeks, $seek);
                  $haystack = substr($haystack, 0, $seek);
              }
              return $seeks;
          }
          it will return an array of all occurrences a the substring in the string
          Example : 
          $test = "this is a test for testing a test function... blah blah";
          var_dump(strpos_r($test, "test"));
          // output 
          array(3) {
            [0]=>
            int(29)
            [1]=>
            int(19)
            [2]=>
            int(10)
          }
          Paul-antoine
          Malézieux.

          Contributed By: rjeggens

          I lost an hour before I noticed that strpos only returns FALSE as a boolean, never TRUE.. This means that
          strpos() !== false 
          is a different beast then:
          strpos() === true
          since the latter will never be true. After I found out, The warning in the documentation made a lot more sense.

          Contributed By: akarmenia

          My version of strpos with needles as an array. Also allows for a string, or an array inside an array.
          <?php
          function strpos_array($haystack, $needles) {
              if ( is_array($needles) ) {
                  foreach ($needles as $str) {
                      if ( is_array($str) ) {
                          $pos = strpos_array($haystack, $str);
                      } else {
                          $pos = strpos($haystack, $str);
                      }
                      if ($pos !== FALSE) {
                          return $pos;
                      }
                  }
              } else {
                  return strpos($haystack, $needles);
              }
          }
          // Test
          echo strpos_array('This is a test', array('test', 'drive')); // Output is 10
          ?>

          PHP strrchr() Function

          What does strrchr() do?

          The PHP strrchr() function will find the last occurrence of a character in a string.

          PHP strrchr() Syntax

           strrchr ( string $haystack , mixed $needle ) : string

          PHP strrchr() Parameters

          1. haystack — The string to search in

          2. needle — If needle contains more than one character, only the first is used. This behavior is different from that of strstr().

          PHP strrchr() Return Value

          The PHP strrchr() function returns the portion of string, or FALSE if needle is not found.

          PHP strrchr() Working Examples

          1. strrchr() example

          <?php
          // get last directory in $PATH
          $dir = substr(strrchr($PATH, ":"), 1);
          // get everything after last newline
          $text = "Line 1\nLine 2\nLine 3";
          $last = substr(strrchr($text, 10), 1 );
          ?>

          Additional Tips from Fellow Developers

          Contributed By: jphansen

          To extract your portion of a string without the actual character you searched for, you can use:
          <?php
          $path = '/www/public_html/index.html';
          $filename = substr(strrchr($path, "/"), 1);
          echo $filename; // "index.html"
          ?>

          Contributed By: matthewkastor

          <?php 
          /** 
           * Removes the preceeding or proceeding portion of a string 
           * relative to the last occurrence of the specified character. 
           * The character selected may be retained or discarded. 
           * 
           * Example usage: 
           * <code> 
           * $example = 'http://example.com/path/file.php'; 
           * $cwd_relative[] = cut_string_using_last('/', $example, 'left', true); 
           * $cwd_relative[] = cut_string_using_last('/', $example, 'left', false); 
           * $cwd_relative[] = cut_string_using_last('/', $example, 'right', true); 
           * $cwd_relative[] = cut_string_using_last('/', $example, 'right', false); 
           * foreach($cwd_relative as $string) { 
           *     echo "$string <br>".PHP_EOL; 
           * } 
           * </code> 
           * 
           * Outputs: 
           * <code> 
           * http://example.com/path/ 
           * http://example.com/path 
           * /file.php 
           * file.php 
           * </code> 
           * 
           * @param string $character the character to search for. 
           * @param string $string the string to search through. 
           * @param string $side determines whether text to the left or the right of the character is returned. 
           * Options are: left, or right. 
           * @param bool $keep_character determines whether or not to keep the character. 
           * Options are: true, or false. 
           * @return string 
           */ 
          function cut_string_using_last($character, $string, $side, $keep_character=true) { 
              $offset = ($keep_character ? 1 : 0); 
              $whole_length = strlen($string); 
              $right_length = (strlen(strrchr($string, $character)) - 1); 
              $left_length = ($whole_length - $right_length - 1); 
              switch($side) { 
                  case 'left': 
                      $piece = substr($string, 0, ($left_length + $offset)); 
                      break; 
                  case 'right': 
                      $start = (0 - ($right_length + $offset)); 
                      $piece = substr($string, $start); 
                      break; 
                  default: 
                      $piece = false; 
                      break; 
              } 
              return($piece); 
          } 
          ?>

          PHP strrev() Function

          What does strrev() do?

          The PHP strrev() function will give you string, reversed.

          PHP strrev() Syntax

           strrev ( string $string ) : string

          PHP strrev() Parameters

          1. string — The string to be reversed.

          PHP strrev() Return Value

          The PHP strrev() function returns the reversed string.

          PHP strrev() Working Examples

          1. Reversing a string with strrev()

          <?php
          echo strrev("Hello world!"); // outputs "!dlrow olleH"
          ?>

          PHP strripos() Function

          What does strripos() do?

          The PHP strripos() function will find the position of the last occurrence of a case-insensitive substring in a string.

          PHP strripos() Syntax

           strripos ( string $haystack , mixed $needle [, int $offset = 0 ] ) : int

          PHP strripos() Parameters

          1. haystack — The string to search in.

          2. needle — If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

          3. offset — If zero or positive, the search is performed left to right skipping the first offset bytes of the haystack.

          PHP strripos() Return Value

          The PHP strripos() function returns the position where the needle exists relative to the beginnning of the haystack string (independent of search direction or offset).

          PHP strripos() Working Examples

          1. A simple strripos() example

          <?php
          $haystack = 'ababcd';
          $needle   = 'aB';
          $pos      = strripos($haystack, $needle);
          if ($pos === false) {
              echo "Sorry, we did not find ($needle) in ($haystack)";
          } else {
              echo "Congratulations!\n";
              echo "We found the last ($needle) in ($haystack) at position ($pos)";
          }
          ?>

          Output of the above code:

           Congratulations!
           We found the last (aB) in (ababcd) at position (2)

          Important Points about PHP strripos() Function

          1. This is effectively looking for the last occurrence of needle before the last offset bytes.

          2. This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

          PHP strrpos() Function

          What does strrpos() do?

          The PHP strrpos() function will find the position of the last occurrence of a substring in a string.

          PHP strrpos() Syntax

           strrpos ( string $haystack , mixed $needle [, int $offset = 0 ] ) : int

          PHP strrpos() Parameters

          1. haystack — The string to search in.

          2. needle — If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

          3. offset — If zero or positive, the search is performed left to right skipping the first offset bytes of the haystack.

          PHP strrpos() Return Value

          The PHP strrpos() function returns the position where the needle exists relative to the beginning of the haystack string (independent of search direction or offset).

          PHP strrpos() Working Examples

          1. Checking if a needle is in the haystack

          <?php
          $pos = strrpos($mystring, "b");
          if ($pos === false) { // note: three equal signs
              // not found...
          }
          ?>

          2. Searching with offsets

          <?php
          $foo = "0123456789a123456789b123456789c";
          // Looking for '0' from the 0th byte (from the beginning)
          var_dump(strrpos($foo, '0', 0));
          // Looking for '0' from the 1st byte (after byte "0")
          var_dump(strrpos($foo, '0', 1));
          // Looking for '7' from the 21th byte (after byte 20)
          var_dump(strrpos($foo, '7', 20));
          // Looking for '7' from the 29th byte (after byte 28)
          var_dump(strrpos($foo, '7', 28));
          // Looking for '7' right to left from the 5th byte from the end
          var_dump(strrpos($foo, '7', -5));
          // Looking for 'c' right to left from the 2nd byte from the end
          var_dump(strrpos($foo, 'c', -2));
          // Looking for '9c' right to left from the 2nd byte from the end
          var_dump(strrpos($foo, '9c', -2));
          ?>

          Output of the above code:

          int(0)
          bool(false)
          int(27)
          bool(false)
          int(17)
          bool(false)
          int(29)

          Important Points about PHP strrpos() Function

          1. This is effectively looking for the last occurrence of needle before the last offset bytes.

          2. This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

          Additional Tips from Fellow Developers

          Contributed By: brian

          The documentation for 'offset' is misleading.
          It says, "offset may be specified to begin searching an arbitrary number of characters into the string. Negative values will stop searching at an arbitrary point prior to the end of the string."
          This is confusing if you think of strrpos as starting at the end of the string and working backwards.
          A better way to think of offset is:
          - If offset is positive, then strrpos only operates on the part of the string from offset to the end. This will usually have the same results as not specifying an offset, unless the only occurences of needle are before offset (in which case specifying the offset won't find the needle).
          - If offset is negative, then strrpos only operates on that many characters at the end of the string. If the needle is farther away from the end of the string, it won't be found.
          If, for example, you want to find the last space in a string before the 50th character, you'll need to do something like this:
          strrpos($text, " ", -(strlen($text) - 50));
          If instead you used strrpos($text, " ", 50), then you would find the last space between the 50th character and the end of the string, which may not have been what you were intending.

          PHP strspn() Function

          What does strspn() do?

          The PHP strspn() function will finds the length of the initial segment of a string consisting entirely of characters contained within a given mask .

          PHP strspn() Syntax

           strspn ( string $subject , string $mask [, int $start [, int $length ]] ) : int

          PHP strspn() Parameters

          1. subject — The string to examine.

          2. mask — The list of allowable characters.

          3. start — The position in subject to start searching.

          4. length — The length of the segment from subject to examine.

          PHP strspn() Return Value

          The PHP strspn() function returns the length of the initial segment of subject which consists entirely of characters in mask.

          PHP strspn() Working Examples

          1. strspn() example

          <?php
          // subject does not start with any characters from mask
          var_dump(strspn("foo", "o"));
          // examine two characters from subject starting at offset 1
          var_dump(strspn("foo", "o", 1, 2));
          // examine one character from subject starting at offset 1
          var_dump(strspn("foo", "o", 1, 1));
          ?>

          Output of the above code:

          int(0)
          int(2)
          int(1)

          Important Points about PHP strspn() Function

          1. When a start parameter is set, the returned length is counted starting from this position, not from the beginning of subject.

          Additional Tips from Fellow Developers

          Contributed By:

          You can use this function with strlen to check illegal characters, string lenght must be the same than strspn (characters from my string contained in another)
          <?php
          $digits='0123456789';
          if (strlen($phone) != strspn($phone,$digits))
           echo "illegal characters";
          ?>

          Contributed By: barry dot balkowski

          It took me some time to understand the way this function works…
          I’ve compiled my own explanation with my own words that is more understandable for me personally than the official one or those that can be found in different tutorials on the web.
          Perhaps, it will save someone several minutes…
          <?php 
          strspn(string $haystack, string $char_list [, int $start [, int $length]])
          ?>
          The way it works:
           -   searches for a segment of $haystack that consists entirely from supplied through the second argument chars 
           -   $haystack must start from one of the chars supplied through $char_list, otherwise the function will find nothing
           -   as soon as the function encounters a char that was not mentioned in $chars it understands that the segment is over and stops (it doesn’t search for the second, third and so on segments)
           -   finally, it measures the segment’s length and return it (i.e. length)
          In other words it finds a span (only the first one) in the string that consists entirely form chars supplied in $chars_list and returns its length

          PHP strstr() Function

          What does strstr() do?

          The PHP strstr() function will give you part of haystack string starting from and including the first occurrence of needle to the end of haystack.

          PHP strstr() Syntax

           strstr ( string $haystack , mixed $needle [, bool $before_needle = FALSE ] ) : string

          PHP strstr() Parameters

          1. haystack — The input string.

          2. needle — If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

          3. before_needle — If TRUE, strstr() returns the part of the haystack before the first occurrence of the needle (excluding the needle).

          PHP strstr() Return Value

          The PHP strstr() function returns the portion of string, or FALSE if needle is not found.

          PHP strstr() Working Examples

          1. strstr() example

          <?php
          $email  = 'name@example.com';
          $domain = strstr($email, '@');
          echo $domain; // prints @example.com
          $user = strstr($email, '@', true); // As of PHP 5.3.0
          echo $user; // prints name
          ?>

          Changelog for PHP strstr() Function

          5.3.0 — Added the optional parameter before_needle.

          Important Points about PHP strstr() Function

          1. This function is case-sensitive. For case-insensitive searches, use stristr().

          2. If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead.

          Additional Tips from Fellow Developers

          Contributed By: laszlo dot heredy

          Strstr() is not a way to avoid type-checking with strpos().
          If $needle is the last character in $haystack, and testing $needle as a boolean by itself would evaluate to false, then testing strstr() as a boolean will evaluate to false (because, if successful, strstr() returns the first occurrence of $needle along with the rest of $haystack).
          <?php
          findZero('01234');  // found a zero
          findZero('43210');  // did not find a zero
          findZero('0');      // did not find a zero
          findZero('00');     // found a zero
          findZero('000');    // found a zero
          findZero('10');     // did not find a zero
          findZero('100');    // found a zero
          function findZero($numberString) {
              if (strstr($numberString, '0')) {
                  echo 'found a zero';
              } else {
                  echo 'did not find a zero';
              }
          }
          ?>
          Also, strstr() is far more memory-intensive than strpos(), especially with longer strings as your $haystack, so if you are not interested in the substring that strstr() returns, you shouldn't be using it anyway. 
          There is no PHP function just to check only _if_ $needle occurs in $haystack; strpos() tells you if it _doesn't_ by returning false, but, if it does occur, it tells you _where_ it occurs as an integer, which is 0 (zero) if $needle is the first part of $haystack, which is why testing if (strpos($needle, $haystack)===false) is the only way to know for sure if $needle is not part of $haystack.
          My advice is to start loving type checking immediately, and to familiarize yourself with the return value of the functions you are using.
          Cheers.

          Contributed By: gruessle

          Been using this for years:
          <?php
          /**
          *
          * @author : Dennis T Kaplan
          *
          * @version : 1.0
          * Date : June 17, 2007
          * Function : reverse strstr()
          * Purpose : Returns part of haystack string from start to the first occurrence of needle
          * $haystack = 'this/that/whatever';
          * $result = rstrstr($haystack, '/')
          * $result == this
          *
          * @access public
          * @param string $haystack, string $needle
          * @return string
          **/
          function rstrstr($haystack,$needle)
              {
                  return substr($haystack, 0,strpos($haystack, $needle));
              }
          ?>
          You could change it to:
          rstrstr ( string $haystack , mixed $needle [, int $start] )
          <?php
          function rstrstr($haystack,$needle, $start=0)
              {
                  return substr($haystack, $start,strpos($haystack, $needle));
              }
          ?>

          PHP strtok() Function

          What does strtok() do?

          The PHP strtok() function will strtok() splits a string (str) into smaller strings (tokens), with each token being delimited by any character from token. That is, if you have a string like “This is an example string” you could tokenize this string into its individual words by using the space character as the token.

          PHP strtok() Syntax

           strtok ( string $str , string $token ) : string
           strtok ( string $token ) : string

          PHP strtok() Parameters

          1. str — The string being split up into smaller strings (tokens).

          2. token — The delimiter used when splitting up str.

          PHP strtok() Return Value

          The PHP strtok() function returns a string token.

          PHP strtok() Working Examples

          1. strtok() example

          <?php
          $string = "This is\tan example\nstring";
          /* Use tab and newline as tokenizing characters as well  */
          $tok = strtok($string, " \n\t");
          while ($tok !== false) {
              echo "Word=$tok<br />";
              $tok = strtok(" \n\t");
          }
          ?>

          2. strtok() behavior on empty part found

          <?php
          $first_token  = strtok('/something', '/');
          $second_token = strtok('/');
          var_dump($first_token, $second_token);
          ?>

          Output of the above code:

           string(9) "something"
           bool(false)

          Important Points about PHP strtok() Function

          1. This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

          Additional Tips from Fellow Developers

          Contributed By: eep2004

          <?php
          // strtok example
          $str = 'Hello to all of Ukraine';
          echo strtok($str, ' ').' '.strtok(' ').' '.strtok(' ');
          ?>
          Result:
          Hello to all

          Contributed By: manicdepressive

          <pre><?php
          /** get leading, trailing, and embedded separator tokens that were 'skipped'
          if for some ungodly reason you are using php to implement a simple parser that 
          needs to detect nested clauses as it builds a parse tree */
          $str = "(((alpha(beta))(gamma))";
          $seps = '()';
          $tok = strtok( $str,$seps ); // return false on empty string or null
          $cur = 0;      
          $dumbDone = FALSE;
          $done = (FALSE===$tok);
          while (!$done) {
             // process skipped tokens (if any at first iteration) (special for last)
             $posTok = $dumbDone ? strlen($str) : strpos($str, $tok, $cur );
             $skippedMany = substr( $str, $cur, $posTok-$cur ); // false when 0 width
             $lenSkipped = strlen($skippedMany); // 0 when false
             if (0!==$lenSkipped) {
                $last = strlen($skippedMany) -1;
                for($i=0; $i<=$last; $i++){
                   $skipped = $skippedMany[$i];
                   $cur += strlen($skipped);
                   echo "skipped: $skipped\n";
                }
             }
             if ($dumbDone) break; // this is the only place the loop is terminated
             // process current tok
             echo "curr tok: ".$tok."\n";
             // update cursor
             $cur += strlen($tok);
             // get any next tok
             if (!$dumbDone){
                $tok = strtok($seps);
                $dumbDone = (FALSE===$tok); 
                // you're not really done till you check for trailing skipped
             }
          };
          ?></pre>

          PHP strtolower() Function

          What does strtolower() do?

          The PHP strtolower() function will give you string with all alphabetic characters converted to lowercase.

          PHP strtolower() Syntax

           strtolower ( string $string ) : string

          PHP strtolower() Parameters

          1. string — The input string.

          PHP strtolower() Return Value

          The PHP strtolower() function returns the lowercased string.

          PHP strtolower() Working Examples

          1. strtolower() example

          <?php
          $str = "Mary Had A Little Lamb and She LOVED It So";
          $str = strtolower($str);
          echo $str; // Prints mary had a little lamb and she loved it so
          ?>

          Additional Tips from Fellow Developers

          Contributed By: marcin

          Strtolower(); doesn't work for polish chars 
           
          <?php strtolower("mĄkA"); ?> 
          will return: mĄka; 
           
          the best solution - use mb_strtolower() 
           
          <?php mb_strtolower("mĄkA",'UTF-8'); ?> 
          will return: mąka

          Contributed By: coder

          For cyrillic and UTF 8 use  mb_convert_case 
           
          exampel 
           
          <?php 
          $string = "Австралия"; 
          $string = mb_convert_case($string, MB_CASE_LOWER, "UTF-8"); 
          echo $string; 
           
          //output is: австралия 
          ?>

          Contributed By: helvete

          It is worth noting that 
          <?php 
          var_dump(strtolower(null))
          ?>
          returns: 
          string(0) ""

          Contributed By: dbers26

          The function  arraytolower will create duplicate entries since keys are case sensitive.  
           
          <?php 
          $array = array('test1' => 'asgAFasDAAd', 'TEST2' => 'ASddhshsDGb', 'TeSt3 '=> 'asdasda@asdadadASDASDgh'); 
           
          $array = arraytolower($array); 
          ?> 
          /* 
          Array 
          ( 
              [test1] => asgafasdaad 
              [TEST2] => ASddhshsDGb 
              [TeSt3] => asdasda@asdadadASDASDgh 
              [test2] => asddhshsdgb 
              [test3] => asdasda@asdadadasdasdgh 
          ) 
          */ 
           
          I prefer this method 
           
          <?php 
            function arraytolower($array, $include_leys=false) { 
              
              if($include_leys) { 
                foreach($array as $key => $value) { 
                  if(is_array($value)) 
                    $array2[strtolower($key)] = arraytolower($value, $include_leys); 
                  else 
                    $array2[strtolower($key)] = strtolower($value); 
                } 
                $array = $array2; 
              } 
              else { 
                foreach($array as $key => $value) { 
                  if(is_array($value)) 
                    $array[$key] = arraytolower($value, $include_leys); 
                  else 
                    $array[$key] = strtolower($value);   
                } 
              } 
              
              return $array; 
            } 
          ?> 
           
          which when used like this 
           
          <?php 
          $array = $array = array('test1' => 'asgAFasDAAd', 'TEST2' => 'ASddhshsDGb', 'TeSt3 '=> 'asdasda@asdadadASDASDgh'); 
           
          $array1 = arraytolower($array); 
          $array2 = arraytolower($array,true); 
           
          print_r($array1); 
          print_r($array2); 
          ?> 
           
          will give output of 
           
          Array 
          ( 
              [test1] => asgafasdaad 
              [TEST2] => asddhshsdgb 
              [TeSt3] => asdasda@asdadadasdasdgh 
          ) 
          Array 
          ( 
              [test1] => asgafasdaad 
              [test2] => asddhshsdgb 
              [test3] => asdasda@asdadadasdasdgh 
          )

          PHP strtoupper() Function

          What does strtoupper() do?

          The PHP strtoupper() function will give you string with all alphabetic characters converted to uppercase.

          PHP strtoupper() Syntax

           strtoupper ( string $string ) : string

          PHP strtoupper() Parameters

          1. string — The input string.

          PHP strtoupper() Return Value

          The PHP strtoupper() function returns the uppercased string.

          PHP strtoupper() Working Examples

          1. strtoupper() example

          <?php
          $str = "Mary Had A Little Lamb and She LOVED It So";
          $str = strtoupper($str);
          echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
          ?>

          Additional Tips from Fellow Developers

          Contributed By: andre

          One might think that setting the correct locale would do the trick with for example german umlauts, but this is not the case. You have to use mb_strtoupper() instead:
          <?php
          setlocale(LC_CTYPE, 'de_DE.UTF8');
          echo strtoupper('Umlaute äöü in uppercase'); // outputs "UMLAUTE äöü IN UPPERCASE"
          echo mb_strtoupper('Umlaute äöü in uppercase', 'UTF-8'); // outputs "UMLAUTE ÄÖÜ IN UPPERCASE"
          ?>

          Contributed By: mec

          Something I myself first not thought about:
          if there are any html entities (named entities) in your string, strtoupper will turn all letters within this entities to upper case, too. So if you want to manipulate a string with strtoupper it should contain only unicode entities (if ever).

          PHP strtr() Function

          What does strtr() do?

          The PHP strtr() function will translate characters or replace substrings.

          PHP strtr() Syntax

           strtr ( string $str , string $from , string $to ) : string
           strtr ( string $str , array $replace_pairs ) : string

          PHP strtr() Parameters

          1. str — The string being translated.

          2. from — The string being translated to to.

          3. to — The string replacing from.

          4. replace_pairs — The replace_pairs parameter may be used instead of to and from, in which case it’s an array in the form array(‘from’ => ‘to’, …).

          PHP strtr() Return Value

          The PHP strtr() function returns the translated string.

          PHP strtr() Working Examples

          1. strtr() example

          <?php
          //In this form, strtr() does byte-by-byte translation
          //Therefore, we are assuming a single-byte encoding here:
          $addr = strtr($addr, "äåö", "aao");
          ?>

          2. strtr() example with two arguments

          <?php
          $trans = array("h" => "-", "hello" => "hi", "hi" => "hello");
          echo strtr("hi all, I said hello", $trans);
          ?>

          Output of the above code:

          hello all, I said hi

          3. strtr() behavior comparison

          <?php
          echo strtr("baab", "ab", "01"),"\n";
          $trans = array("ab" => "01");
          echo strtr("baab", $trans);
          ?>

          Output of the above code:

          1001
          ba01

          Additional Tips from Fellow Developers

          Contributed By: evan dot king

          Here's an important real-world example use-case for strtr where str_replace will not work or will introduce obscure bugs:
          <?php
          $strTemplate = "My name is :name, not :name2.";
          $strParams = [
            ':name' => 'Dave',
            'Dave' => ':name2 or :password', // a wrench in the otherwise sensible input
            ':name2' => 'Steve',
            ':pass' => '7hf2348', // sensitive data that maybe shouldn't be here
          ];
          echo strtr($strTemplate, $strParams);
          // "My name is Dave, not Steve."
          echo str_replace(array_keys($strParams), array_values($strParams), $strTemplate);
          // "My name is Steve or 7hf2348word, not Steve or 7hf2348word2."
          ?>
          Any time you're trying to template out a string and don't necessarily know what the replacement keys/values will be (or fully understand the implications of and control their content and order), str_replace will introduce the potential to incorrectly match your keys because it does not expand the longest keys first.
          Further, str_replace will replace in previous replacements, introducing potential for unintended nested expansions.  Doing so can put the wrong data into the "sub-template" or even give users a chance to provide input that exposes data (if they get to define some of the replacement strings).
          Don't support recursive expansion unless you need it and know it will be safe.  When you do support it, do so explicitly by repeating strtr calls until no more expansions are occurring or a sane iteration limit is reached, so that the results never implicitly depend on order of your replacement keys.  Also make certain that any user input will expanded in an isolated step after any sensitive data is already expanded into the output and no longer available as input.
          Note: using some character(s) around your keys to designate them also reduces the possibility of unintended mangling of output, whether maliciously triggered or otherwise.  Thus the use of a colon prefix in these examples, which you can easily enforce when accepting replacement input to your templating/translation system.

          Contributed By:

          Since strtr (like PHP's other string functions) treats strings as a sequence of bytes, and since UTF-8 and other multibyte encodings use - by definition - more than one byte for at least some characters, the three-string form is likely to have problems. Use the associative array form to specify the mapping.
          <?php
          // Assuming UTF-8
          $str = 'Äbc Äbc'; // strtr() sees this as nine bytes (including two for each Ä)
          echo strtr($str, 'Ä', 'a'); // The second argument is equivalent to the string "\xc3\x84" so "\xc3" gets replaced by "a" and the "\x84" is ignored
          echo strtr($str, array('Ä' => 'a')); // Works much better
          ?>

          Contributed By: allixsenos

          Fixed "normaliza" functions written below to include Slavic Latin characters... also, it doesn't return lowercase any more (you can easily get that by applying strtolower yourself)...
          also, renamed to normalize()
          <?php
          function normalize ($string) {
              $table = array(
                  'Š'=>'S', 'š'=>'s', 'Đ'=>'Dj', 'đ'=>'dj', 'Ž'=>'Z', 'ž'=>'z', 'Č'=>'C', 'č'=>'c', 'Ć'=>'C', 'ć'=>'c',
                  'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
                  'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
                  'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss',
                  'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
                  'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
                  'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
                  'ÿ'=>'y', 'Ŕ'=>'R', 'ŕ'=>'r',
              );
              
              return strtr($string, $table);
          }
          ?>

          Contributed By: dot dot dot dot dot alexander

          OK, I debugged the function (had some errors)
          Here it is:
          if(!function_exists("stritr")){
              function stritr($string, $one = NULL, $two = NULL){
          /*
          stritr - case insensitive version of strtr
          Author: Alexander Peev
          Posted in PHP.NET
          */
                  if(  is_string( $one )  ){
                      $two = strval( $two );
                      $one = substr(  $one, 0, min( strlen($one), strlen($two) )  );
                      $two = substr(  $two, 0, min( strlen($one), strlen($two) )  );
                      $product = strtr(  $string, ( strtoupper($one) . strtolower($one) ), ( $two . $two )  );
                      return $product;
                  }
                  else if(  is_array( $one )  ){
                      $pos1 = 0;
                      $product = $string;
                      while(  count( $one ) > 0  ){
                          $positions = array();
                          foreach(  $one as $from => $to  ){
                              if(   (  $pos2 = stripos( $product, $from, $pos1 )  ) === FALSE   ){
                                  unset(  $one[ $from ]  );
                              }
                              else{
                                  $positions[ $from ] = $pos2;
                              }
                          }
                          if(  count( $one ) <= 0  )break;
                          $winner = min( $positions );
                          $key = array_search(  $winner, $positions  );
                          $product = (   substr(  $product, 0, $winner  ) . $one[$key] . substr(  $product, ( $winner + strlen($key) )  )   );
                          $pos1 = (  $winner + strlen( $one[$key] )  );
                      }
                      return $product;
                  }
                  else{
                      return $string;
                  }
              }/* endfunction stritr */
          }/* endfunction exists stritr */

          PHP substr() Function

          What does substr() do?

          The PHP substr() function will give you the portion of string specified by the start and length parameters.

          PHP substr() Syntax

           substr ( string $string , int $start [, int $length ] ) : string

          PHP substr() Parameters

          1. string — The input string. Must be one character or longer.

          2. start — If start is non-negative, the returned string will start at the start’th position in string, counting from zero. For instance, in the string ‘abcdef’, the character at position 0 is ‘a’, the character at position 2 is ‘c’, and so forth.

          3. length — If length is given and is positive, the string returned will contain at most length characters beginning from start (depending on the length of string).

          PHP substr() Return Value

          The PHP substr() function returns the extracted part of string; or FALSE on failure, or an empty string.

          PHP substr() Working Examples

          1. Using a negative start

          <?php
          $rest = substr("abcdef", -1);    // returns "f"
          $rest = substr("abcdef", -2);    // returns "ef"
          $rest = substr("abcdef", -3, 1); // returns "d"
          ?>

          2. Using a negative length

          <?php
          $rest = substr("abcdef", 0, -1);  // returns "abcde"
          $rest = substr("abcdef", 2, -1);  // returns "cde"
          $rest = substr("abcdef", 4, -4);  // returns false
          $rest = substr("abcdef", -3, -1); // returns "de"
          ?>

          3. Basic substr() usage

          <?php
          echo substr('abcdef', 1);     // bcdef
          echo substr('abcdef', 1, 3);  // bcd
          echo substr('abcdef', 0, 4);  // abcd
          echo substr('abcdef', 0, 8);  // abcdef
          echo substr('abcdef', -1, 1); // f
          // Accessing single characters in a string
          // can also be achieved using "square brackets"
          $string = 'abcdef';
          echo $string[0];                 // a
          echo $string[3];                 // d
          echo $string[strlen($string)-1]; // f
          ?>

          4. substr() casting behaviour

          <?php
          class apple {
              public function __toString() {
                  return "green";
              }
          }
          echo "1) ".var_export(substr("pear", 0, 2), true).PHP_EOL;
          echo "2) ".var_export(substr(54321, 0, 2), true).PHP_EOL;
          echo "3) ".var_export(substr(new apple(), 0, 2), true).PHP_EOL;
          echo "4) ".var_export(substr(true, 0, 1), true).PHP_EOL;
          echo "5) ".var_export(substr(false, 0, 1), true).PHP_EOL;
          echo "6) ".var_export(substr("", 0, 1), true).PHP_EOL;
          echo "7) ".var_export(substr(1.2e3, 0, 4), true).PHP_EOL;
          ?>

          Output of the above code:

          1) 'pe'
          2) '54'
          3) 'gr'
          4) '1'
          5) ''
          6) ''
          7) '1200'

          Changelog for PHP substr() Function

          7.0.0 — If string is equal to start characters long, an empty string will be returned. Prior to this version, FALSE was returned in this case.

          5.2.2 – 5.2.6 — If the start parameter indicates the position of a negative truncation or beyond, false is returned. Other versions get the string from start.

          Additional Tips from Fellow Developers

          Contributed By: Andreas Bur (andreas dot buro

          For getting a substring of UTF-8 characters, I highly recommend mb_substr
          <?php
                  $utf8string = "cakeæøå";
                  echo substr($utf8string,0,5);
                  // output cake#
                  echo mb_substr($utf8string,0,5,'UTF-8');
                  //output cakeæ
          ?>

          Contributed By: biohazard dot ge

          May be by following functions will be easier to extract the needed sub parts from a string:
          <?php
          after ('@', 'biohazard@online.ge');
          //returns 'online.ge'
          //from the first occurrence of '@'
          before ('@', 'biohazard@online.ge');
          //returns 'biohazard'
          //from the first occurrence of '@'
          between ('@', '.', 'biohazard@online.ge');
          //returns 'online'
          //from the first occurrence of '@'
          after_last ('[', 'sin[90]*cos[180]');
          //returns '180]'
          //from the last occurrence of '['
          before_last ('[', 'sin[90]*cos[180]');
          //returns 'sin[90]*cos['
          //from the last occurrence of '['
          between_last ('[', ']', 'sin[90]*cos[180]');
          //returns '180'
          //from the last occurrence of '['
          ?>
          here comes the source:
          <?php
              function after ($this, $inthat)
              {
                  if (!is_bool(strpos($inthat, $this)))
                  return substr($inthat, strpos($inthat,$this)+strlen($this));
              };
              function after_last ($this, $inthat)
              {
                  if (!is_bool(strrevpos($inthat, $this)))
                  return substr($inthat, strrevpos($inthat, $this)+strlen($this));
              };
              function before ($this, $inthat)
              {
                  return substr($inthat, 0, strpos($inthat, $this));
              };
              function before_last ($this, $inthat)
              {
                  return substr($inthat, 0, strrevpos($inthat, $this));
              };
              function between ($this, $that, $inthat)
              {
                  return before ($that, after($this, $inthat));
              };
              function between_last ($this, $that, $inthat)
              {
               return after_last($this, before_last($that, $inthat));
              };
          // use strrevpos function in case your php version does not include it
          function strrevpos($instr, $needle)
          {
              $rev_pos = strpos (strrev($instr), strrev($needle));
              if ($rev_pos===false) return false;
              else return strlen($instr) - $rev_pos - strlen($needle);
          };
          ?>

          Contributed By: pugazhenthi k

          <?Php 
          ### SUB STRING  BY WORD USING substr() and strpos()  #####
          ### THIS SCRIPT WILL RETURN PART OF STRING  WITHOUT WORD BREAK ###
          $description = ‘your description here your description here your description here your description here your description here your description here your description hereyour description here your description here’  // your description here .
          $no_letter = 30 ;
          if(strlen($desctiption) > 30 )
          {
               echo substr($description,0,strpos($description,’ ‘,30));             //strpos to find ‘ ‘ after 30 characters.
          }
          else {
               echo $description;
          }
          ?>

          PHP substr_compare() Function

          What does substr_compare() do?

          The PHP substr_compare() function will binary safe comparison of two strings from an offset, up to length characters.

          PHP substr_compare() Syntax

           substr_compare ( string $main_str , string $str , int $offset [, int $length [, bool $case_insensitivity = FALSE ]] ) : int

          PHP substr_compare() Parameters

          1. main_str — The main string being compared.

          2. str — The secondary string being compared.

          3. offset — The start position for the comparison. If negative, it starts counting from the end of the string.

          4. length — The length of the comparison. The default value is the largest of the length of the str compared to the length of main_str minus the offset.

          5. case_insensitivity — If case_insensitivity is TRUE, comparison is case insensitive.

          PHP substr_compare() Return Value

          The PHP substr_compare() function returns < 0 if main_str from position offset is less than str, > 0 if it is greater than str, and 0 if they are equal. If offset is equal to (prior to PHP 7.2.18, 7.3.5) or greater than the length of main_str, or the length is set and is less than 0, (or, prior to PHP 5.5.11, less than 1) substr_compare() prints a warning and return FALSE.

          PHP substr_compare() Working Examples

          1. A substr_compare() example

          <?php
          echo substr_compare("abcde", "bc", 1, 2); // 0
          echo substr_compare("abcde", "de", -2, 2); // 0
          echo substr_compare("abcde", "bcg", 1, 2); // 0
          echo substr_compare("abcde", "BC", 1, 2, true); // 0
          echo substr_compare("abcde", "bc", 1, 3); // 1
          echo substr_compare("abcde", "cd", 1, 2); // -1
          echo substr_compare("abcde", "abc", 5, 1); // warning
          ?>

          Changelog for PHP substr_compare() Function

          7.2.18, 7.3.5 — offset may now be equal to the length of main_str.

          5.5.11 — length may now be 0.

          5.1.0 — Added the possibility to use a negative offset.

          Additional Tips from Fellow Developers

          Contributed By: jimmetry

          When you came to this page, you may have been looking for something a little simpler: A function that can check if a small string exists within a larger string starting at a particular index. Using substr_compare() for this can leave your code messy, because you need to check that your string is long enough (to avoid the warning), manually specify the length of the short string, and like many of the string functions, perform an integer comparison to answer a true/false question.
          I put together a simple function to return true if $str exists within $mainStr. If $loc is specified, the $str must begin at that index. If not, the entire $mainStr will be searched.
          <?php
          function contains_substr($mainStr, $str, $loc = false) {
              if ($loc === false) return (strpos($mainStr, $str) !== false);
              if (strlen($mainStr) < strlen($str)) return false;
              if (($loc + strlen($str)) > strlen($mainStr)) return false;
              return (strcmp(substr($mainStr, $loc, strlen($str)), $str) == 0);
          }
          ?>

          PHP substr_count() Function

          What does substr_count() do?

          The PHP substr_count() function will count the number of substring occurrences.

          PHP substr_count() Syntax

           substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] ) : int

          PHP substr_count() Parameters

          1. haystack — The string to search in

          2. needle — The substring to search for

          3. offset — The offset where to start counting. If the offset is negative, counting starts from the end of the string.

          4. length — The maximum length after the specified offset to search for the substring. It outputs a warning if the offset plus the length is greater than the haystack length. A negative length counts from the end of haystack.

          PHP substr_count() Return Value

          The PHP substr_count() function returns an integer.

          PHP substr_count() Working Examples

          1. A substr_count() example

          <?php
          $text = 'This is a test';
          echo strlen($text); // 14
          echo substr_count($text, 'is'); // 2
          // the string is reduced to 's is a test', so it prints 1
          echo substr_count($text, 'is', 3);
          // the text is reduced to 's i', so it prints 0
          echo substr_count($text, 'is', 3, 3);
          // generates a warning because 5+10 > 14
          echo substr_count($text, 'is', 5, 10);
          // prints only 1, because it doesn't count overlapped substrings
          $text2 = 'gcdgcdgcd';
          echo substr_count($text2, 'gcdgcd');
          ?>

          Changelog for PHP substr_count() Function

          7.1.0 — Support for negative offsets and lengths has been added. length may also be 0 now.

          5.1.0 — Added the offset and the length parameters

          Important Points about PHP substr_count() Function

          1. This function doesn’t count overlapped substrings. See the example below!

          Additional Tips from Fellow Developers

          Contributed By: tuxedobob

          It's worth noting this function is surprisingly fast. I first ran it against a ~500KB string on our web server. It found 6 occurrences of the needle I was looking for in 0.0000 seconds. Yes, it ran faster than microtime() could measure.
          Looking to give it a challenge, I then ran it on a Mac laptop from 2010 against a 120.5MB string. For one test needle, it found 2385 occurrences in 0.0266 seconds. Another test needs found 290 occurrences in 0.114 seconds.
          Long story short, if you're wondering whether this function is slowing down your script, the answer is probably not.

          PHP substr_replace() Function

          What does substr_replace() do?

          The PHP substr_replace() function will replace text within a portion of a string.

          PHP substr_replace() Syntax

           substr_replace ( mixed $string , mixed $replacement , mixed $start [, mixed $length ] ) : mixed

          PHP substr_replace() Parameters

          1. string — The input string.

          2. replacement — The replacement string.

          3. start — If start is non-negative, the replacing will begin at the start’th offset into string.

          4. length — If given and is positive, it represents the length of the portion of string which is to be replaced. If it is negative, it represents the number of characters from the end of string at which to stop replacing. If it is not given, then it will default to strlen( string ); i.e. end the replacing at the end of string. Of course, if length is zero then this function will have the effect of inserting replacement into string at the given start offset.

          PHP substr_replace() Return Value

          The PHP substr_replace() function returns d. If string is an array then array is returned.

          PHP substr_replace() Working Examples

          1. Simple substr_replace() examples

          <?php
          $var = 'ABCDEFGH:/MNRPQR/';
          echo "Original: $var<hr />\n";
          /* These two examples replace all of $var with 'bob'. */
          echo substr_replace($var, 'bob', 0) . "<br />\n";
          echo substr_replace($var, 'bob', 0, strlen($var)) . "<br />\n";
          /* Insert 'bob' right at the beginning of $var. */
          echo substr_replace($var, 'bob', 0, 0) . "<br />\n";
          /* These next two replace 'MNRPQR' in $var with 'bob'. */
          echo substr_replace($var, 'bob', 10, -1) . "<br />\n";
          echo substr_replace($var, 'bob', -7, -1) . "<br />\n";
          /* Delete 'MNRPQR' from $var. */
          echo substr_replace($var, '', 10, -1) . "<br />\n";
          ?>

          2. Using substr_replace() to replace multiple strings at once

          <?php
          $input = array('A: XXX', 'B: XXX', 'C: XXX');
          // A simple case: replace XXX in each string with YYY.
          echo implode('; ', substr_replace($input, 'YYY', 3, 3))."\n";
          // A more complicated case where each replacement is different.
          $replace = array('AAA', 'BBB', 'CCC');
          echo implode('; ', substr_replace($input, $replace, 3, 3))."\n";
          // Replace a different number of characters each time.
          $length = array(1, 2, 3);
          echo implode('; ', substr_replace($input, $replace, 3, $length))."\n";
          ?>

          Output of the above code:

          A: YYY; B: YYY; C: YYY
          A: AAA; B: BBB; C: CCC
          A: AAAXX; B: BBBX; C: CCC

          Additional Tips from Fellow Developers

          Contributed By: elloromtz

          It's worth noting that when start and length are both negative -and- the length is less than or equal to start, the length will have the effect of being set as 0. 
           
          <?php 
          substr_replace('eggs','x',-1,-1); //eggxs 
          substr_replace('eggs','x',-1,-2); //eggxs 
          substr_replace('eggs','x',-1,-2); //eggxs 
          ?> 
           
          Same as: 
          <?php 
          substr_replace('eggs','x',-1,0); //eggxs 
          ?> 
           
          <?php 
          substr_replace('huevos','x',-2,-2); //huevxos 
          substr_replace('huevos','x',-2,-3); //huevxos 
          substr_replace('huevos','x',-2,-3); //huevxos 
          ?> 
           
          Same as: 
          <?php 
          substr_replace('huevos','x',-2,0); //huevxos 
          ?> 
           
          Another note, if length is negative and start offsets the same position as length, length (yet again) will have the effect as being set as 0. (Of course, as mentioned in the manual, when length is negative it actually represents the position before it) 
           
          <?php 
          substr_replace('abcd', 'x', 0, -4); //xabcd 
          ?> 
           
          Same as: 
          <?php 
          substr_replace('abcd','x',0,0); //xabcd 
          ?> 
           
          <?php 
          substr_replace('abcd', 'x', 1, -3); //axbcd 
          ?> 
           
          Same as: 
          <?php 
          substr_replace('abcd', 'x', 1, 0); //axbcd 
          ?>

          PHP trim() Function

          What does trim() do?

          The PHP trim() function will strip whitespace (or other characters) from the beginning and end of a string.

          PHP trim() Syntax

           trim ( string $str [, string $character_mask = " \t\n\r\0\x0B" ] ) : string

          PHP trim() Parameters

          1. str — The string that will be trimmed.

          2. character_mask — Optionally, the stripped characters can also be specified using the character_mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

          PHP trim() Return Value

          The PHP trim() function returns the trimmed string.

          PHP trim() Working Examples

          1. Usage example of trim()

          <?php
          $text   = "\t\tThese are a few words :) ...  ";
          $binary = "\x09Example string\x0A";
          $hello  = "Hello World";
          var_dump($text, $binary, $hello);
          print "\n";
          $trimmed = trim($text);
          var_dump($trimmed);
          $trimmed = trim($text, " \t.");
          var_dump($trimmed);
          $trimmed = trim($hello, "Hdle");
          var_dump($trimmed);
          $trimmed = trim($hello, 'HdWr');
          var_dump($trimmed);
          // trim the ASCII control characters at the beginning and end of $binary
          // (from 0 to 31 inclusive)
          $clean = trim($binary, "\x00..\x1F");
          var_dump($clean);
          ?>

          Output of the above code:

          string(32) " These are a few words :) ... "
          string(16) " Example string
          "
          string(11) "Hello World"
          string(28) "These are a few words :) ..."
          string(24) "These are a few words :)"
          string(5) "o Wor"
          string(9) "ello Worl"
          string(14) "Example string"

          2. Trimming array values with trim()

          <?php
          function trim_value(&$value) 
          { 
              $value = trim($value); 
          }
          $fruit = array('apple','banana ', ' cranberry ');
          var_dump($fruit);
          array_walk($fruit, 'trim_value');
          var_dump($fruit);
          ?>

          Output of the above code:

          array(3) {
           [0]=>
           string(5) "apple"
           [1]=>
           string(7) "banana "
           [2]=>
           string(11) " cranberry "
          }
          array(3) {
           [0]=>
           string(5) "apple"
           [1]=>
           string(6) "banana"
           [2]=>
           string(9) "cranberry"
          }

          Important Points about PHP trim() Function

          1. Because trim() trims characters from the beginning and end of a string, it may be confusing when characters are (or are not) removed from the middle. trim(‘abc’, ‘bad’) removes both ‘a’ and ‘b’ because it trims ‘a’ thus moving ‘b’ to the beginning to also be trimmed. So, this is why it “works” whereas trim(‘abc’, ‘b’) seemingly does not.

          Additional Tips from Fellow Developers

          Contributed By: Piopier

          It may be useful to know that trim() returns an empty string when the argument is an unset/null variable.

          Contributed By: aalhad

          When specifying the character mask, 
          make sure that you use double quotes
          <?php
            $hello = " 
                Hello World   "; //here is a string with some trailing and leading whitespace
            $trimmed_correct   = trim($hello, " \t\n\r"); //<--------OKAY
            $trimmed_incorrect = trim($hello, ' \t\n\r'); //<--------NOT AS EXPECTED
            print("----------------------------");
            print("TRIMMED OK:".PHP_EOL);
            print_r($trimmed_correct.PHP_EOL);
            print("----------------------------");
            print("TRIMMING NOT OK:".PHP_EOL);
            print_r($trimmed_incorrect.PHP_EOL);
            print("----------------------------".PHP_EOL);
          ?>
          Here is the output:
          ----------------------------TRIMMED OK:
          Hello World
          ----------------------------TRIMMING NOT OK:
                Hello World
          ----------------------------

          Contributed By: ludko2

          Non-breaking spaces can be troublesome with trim: 
           
          <?php 
          // turn some HTML with non-breaking spaces into a "normal" string 
          $myHTML = "&nbsp;abc"; 
          $converted = strtr($myHTML, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES))); 
           
          // this WILL NOT work as expected 
          // $converted will still appear as " abc" in view source 
          // (but not in od -x) 
          $converted = trim($converted); 
           
          // &nbsp; are translated to 0xA0, so use: 
          $converted = trim($converted, "\xA0"); // <- THIS DOES NOT WORK 
           
          // EDITED>> 
          // UTF encodes it as chr(0xC2).chr(0xA0) 
          $converted = trim($converted,chr(0xC2).chr(0xA0)); // should work 
           
          // PS: Thanks to John for saving my sanity! 
          ?>

          Contributed By: jubi

          To remove multiple occurences of whitespace characters in a string an convert them all into single spaces, use this:
          <?
          $text = preg_replace('/\s+/', ' ', $text);
          ?>
          ------------
          JUBI
          http://www.jubi.buum.pl

          PHP ucfirst() Function

          What does ucfirst() do?

          The PHP ucfirst() function will make a string’s first character uppercase.

          PHP ucfirst() Syntax

           ucfirst ( string $str ) : string

          PHP ucfirst() Parameters

          1. str — The input string.

          PHP ucfirst() Return Value

          The PHP ucfirst() function returns the resulting string.

          PHP ucfirst() Working Examples

          1. ucfirst() example

          <?php
          $foo = 'hello world!';
          $foo = ucfirst($foo);             // Hello world!
          $bar = 'HELLO WORLD!';
          $bar = ucfirst($bar);             // HELLO WORLD!
          $bar = ucfirst(strtolower($bar)); // Hello world!
          ?>

          Additional Tips from Fellow Developers

          Contributed By: plemieux

          Simple multi-bytes ucfirst():
          <?php
          function my_mb_ucfirst($str) {
              $fc = mb_strtoupper(mb_substr($str, 0, 1));
              return $fc.mb_substr($str, 1);
          }
          ?>

          Contributed By: prokur.net – there is my email

          I believe that mb_ucfirst will be soon added in PHP, but for now this could be useful
          <?php
          if (!function_exists('mb_ucfirst') && function_exists('mb_substr')) {
              function mb_ucfirst($string) {
                  $string = mb_strtoupper(mb_substr($string, 0, 1)) . mb_substr($string, 1);
                  return $string;
              }
          }
          ?>
          it also check is mb support enabled or not

          Contributed By: mattalexxpub

          This is what I use for converting strings to sentence case: 
           
          <?php 
          function sentence_case($string) { 
              $sentences = preg_split('/([.?!]+)/', $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE); 
              $new_string = ''; 
              foreach ($sentences as $key => $sentence) { 
                  $new_string .= ($key & 1) == 0? 
                      ucfirst(strtolower(trim($sentence))) : 
                      $sentence.' '; 
              } 
              return trim($new_string); 
          } 
           
          print sentence_case('HMM. WOW! WHAT?'); 
           
          // Outputs: "Hmm. Wow! What?" 
          ?>

          PHP ucwords() Function

          What does ucwords() do?

          The PHP ucwords() function will uppercase the first character of each word in a string.

          PHP ucwords() Syntax

           ucwords ( string $str [, string $delimiters = " \t\r\n\f\v" ] ) : string

          PHP ucwords() Parameters

          1. str — The input string.

          2. delimiters — The optional delimiters contains the word separator characters.

          PHP ucwords() Return Value

          The PHP ucwords() function returns the modified string.

          PHP ucwords() Working Examples

          1. ucwords() example

          <?php
          $foo = 'hello world!';
          $foo = ucwords($foo);             // Hello World!
          $bar = 'HELLO WORLD!';
          $bar = ucwords($bar);             // HELLO WORLD!
          $bar = ucwords(strtolower($bar)); // Hello World!
          ?>

          2. ucwords() example with custom delimiter

          <?php
          $foo = 'hello|world!';
          $bar = ucwords($foo);             // Hello|world!
          $baz = ucwords($foo, "|");        // Hello|World!
          ?>

          Changelog for PHP ucwords() Function

          5.4.32, 5.5.16 — Added the delimiters parameter.

          Additional Tips from Fellow Developers

          Contributed By: jmarois

          My quick and dirty ucname (Upper Case Name) function.
          <?php
          //FUNCTION
          function ucname($string) {
              $string =ucwords(strtolower($string));
              foreach (array('-', '\'') as $delimiter) {
                if (strpos($string, $delimiter)!==false) {
                  $string =implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
                }
              }
              return $string;
          }
          ?>
          <?php
          //TEST
          $names =array(
            'JEAN-LUC PICARD',
            'MILES O\'BRIEN',
            'WILLIAM RIKER',
            'geordi la forge',
            'bEvErly CRuSHeR'
          );
          foreach ($names as $name) { print ucname("{$name}\n"); }
          //PRINTS:
          /*
          Jean-Luc Picard
          Miles O'Brien
          William Riker
          Geordi La Forge
          Beverly Crusher
          */
          ?>
          You can add more delimiters in the for-each loop array if you want to handle more characters.

          Contributed By: antoniomax

          Para formatar nomes em pt-br:
          <?php
              function titleCase($string, $delimiters = array(" ", "-", ".", "'", "O'", "Mc"), $exceptions = array("de", "da", "dos", "das", "do", "I", "II", "III", "IV", "V", "VI"))
              {
                  /*
                   * Exceptions in lower case are words you don't want converted
                   * Exceptions all in upper case are any words you don't want converted to title case
                   *   but should be converted to upper case, e.g.:
                   *   king henry viii or king henry Viii should be King Henry VIII
                   */
                  $string = mb_convert_case($string, MB_CASE_TITLE, "UTF-8");
                  foreach ($delimiters as $dlnr => $delimiter) {
                      $words = explode($delimiter, $string);
                      $newwords = array();
                      foreach ($words as $wordnr => $word) {
                          if (in_array(mb_strtoupper($word, "UTF-8"), $exceptions)) {
                              // check exceptions list for any words that should be in upper case
                              $word = mb_strtoupper($word, "UTF-8");
                          } elseif (in_array(mb_strtolower($word, "UTF-8"), $exceptions)) {
                              // check exceptions list for any words that should be in upper case
                              $word = mb_strtolower($word, "UTF-8");
                          } elseif (!in_array($word, $exceptions)) {
                              // convert to uppercase (non-utf8 only)
                              $word = ucfirst($word);
                          }
                          array_push($newwords, $word);
                      }
                      $string = join($delimiter, $newwords);
                 }//foreach
                 return $string;
              }
          ?>
          Usage:
          <?php
              $s = 'SÃO JOÃO DOS SANTOS';
              $v = titleCase($s); // 'São João dos Santos' 
          ?>

          Contributed By: robert

          Some recipes for switching between underscore and camelcase naming: 
           
          <?php 
          // underscored to upper-camelcase 
          // e.g. "this_method_name" -> "ThisMethodName" 
          preg_replace('/(?:^|_)(.?)/e',"strtoupper('$1')",$string); 
           
          // underscored to lower-camelcase 
          // e.g. "this_method_name" -> "thisMethodName" 
          preg_replace('/_(.?)/e',"strtoupper('$1')",$string); 
           
          // camelcase (lower or upper) to underscored 
          // e.g. "thisMethodName" -> "this_method_name" 
          // e.g. "ThisMethodName" -> "this_method_name" 
          strtolower(preg_replace('/([^A-Z])([A-Z])/', "$1_$2", $string)); 
          ?> 
           
          Of course these aren't 100% symmetric.  For example... 
            * this_is_a_string -> ThisIsAString -> this_is_astring 
            * GetURLForString -> get_urlfor_string -> GetUrlforString

          Contributed By: Luca Borrione luca -a email -d c_o_m

          Features: 
          - multi byte compatible 
          - handles multiple delimiters 
           
          <?php 
          function ucwords_specific ($string, $delimiters = '', $encoding = NULL) 
          { 
              if ($encoding === NULL) { $encoding = mb_internal_encoding();} 
           
              if (is_string($delimiters)) 
              { 
                  $delimiters =  str_split( str_replace(' ', '', $delimiters)); 
              } 
           
              $delimiters_pattern1 = array(); 
              $delimiters_replace1 = array(); 
              $delimiters_pattern2 = array(); 
              $delimiters_replace2 = array(); 
              foreach ($delimiters as $delimiter) 
              { 
                  $uniqid = uniqid(); 
                  $delimiters_pattern1[]   = '/'. preg_quote($delimiter) .'/'; 
                  $delimiters_replace1[]   = $delimiter.$uniqid.' '; 
                  $delimiters_pattern2[]   = '/'. preg_quote($delimiter.$uniqid.' ') .'/'; 
                  $delimiters_replace2[]   = $delimiter; 
              } 
           
              // $return_string = mb_strtolower($string, $encoding); 
              $return_string = $string; 
              $return_string = preg_replace($delimiters_pattern1, $delimiters_replace1, $return_string); 
           
              $words = explode(' ', $return_string); 
           
              foreach ($words as $index => $word) 
              { 
                  $words[$index] = mb_strtoupper(mb_substr($word, 0, 1, $encoding), $encoding).mb_substr($word, 1, mb_strlen($word, $encoding), $encoding); 
              } 
           
              $return_string = implode(' ', $words); 
           
              $return_string = preg_replace($delimiters_pattern2, $delimiters_replace2, $return_string); 
           
              return $return_string; 
          } 
          ?> 
           
          Params: 
          1. string: The string being converted 
          2. delimiters: a string with all wanted delimiters written one after the other e.g. "-'" 
          3. encoding: Is the character encoding. If it is omitted, the internal character encoding value will be used. 
           
          Example Usage: 
          <?php 
          mb_internal_encoding('UTF-8'); 
          $string = "JEAN-PAUL d'artagnan şŠ-òÀ-éÌ hello - world"; 
          echo ucwords_specific( mb_strtolower($string, 'UTF-8'), "-'"); 
          ?> 
           
          Output: 
          Jean-Paul D'Artagnan Şš-Òà-Éì Hello - World

          PHP vfprintf() Function

          What does vfprintf() do?

          The PHP vfprintf() function will write a string produced according to format to the stream resource specified by handle.

          PHP vfprintf() Syntax

           vfprintf ( resource $handle , string $format , array $args ) : int

          PHP vfprintf() Parameters

          1. handle

          2. format — The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result and conversion specifications, each of which results in fetching its own parameter.

          3. args

          PHP vfprintf() Return Value

          The PHP vfprintf() function returns the length of the outputted string.

          PHP vfprintf() Working Examples

          1. vfprintf(): zero-padded integers

          <?php
          if (!($fp = fopen('date.txt', 'w')))
              return;
          vfprintf($fp, "%04d-%02d-%02d", array($year, $month, $day));
          // will write the formatted ISO date to date.txt
          ?>

          Important Points about PHP vfprintf() Function

          1. The c type specifier ignores padding and width

          2. Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

          PHP vprintf() Function

          What does vprintf() do?

          The PHP vprintf() function will display array values as a formatted string according to format (which is described in the documentation for sprintf()).

          PHP vprintf() Syntax

           vprintf ( string $format , array $args ) : int

          PHP vprintf() Parameters

          1. format — The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result and conversion specifications, each of which results in fetching its own parameter.

          2. args

          PHP vprintf() Return Value

          The PHP vprintf() function returns the length of the outputted string.

          PHP vprintf() Working Examples

          1. vprintf(): zero-padded integers

          <?php
          vprintf("%04d-%02d-%02d", explode('-', '1988-8-1'));
          ?>

          Output of the above code:

          1988-08-01

          Important Points about PHP vprintf() Function

          1. The c type specifier ignores padding and width

          2. Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

          PHP vsprintf() Function

          What does vsprintf() do?

          The PHP vsprintf() function will operates as sprintf() but accepts an array of arguments, rather than a variable number of arguments.

          PHP vsprintf() Syntax

           vsprintf ( string $format , array $args ) : string

          PHP vsprintf() Parameters

          1. format — The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result and conversion specifications, each of which results in fetching its own parameter.

          2. args

          PHP vsprintf() Return Value

          The PHP vsprintf() function returns

          PHP vsprintf() Working Examples

          1. vsprintf(): zero-padded integers

          <?php
          print vsprintf("%04d-%02d-%02d", explode('-', '1988-8-1'));
          ?>

          Output of the above code:

          1988-08-01

          Important Points about PHP vsprintf() Function

          1. The c type specifier ignores padding and width

          2. Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

          Additional Tips from Fellow Developers

          Contributed By:

          Instead of inventing own functions in case you'd like to use array keys as placeholder names and replace corresponding array values in a string, just use the str_replace:
          $string = 'Hello %name!';
          $data = array(
            '%name' => 'John'
          );
          $greeting = str_replace(array_keys($data), array_values($data), $string);

          Contributed By: Josef Kufner

          <?php 
          /** 
           * Like vsprintf, but accepts $args keys instead of order index. 
           * Both numeric and strings matching /[a-zA-Z0-9_-]+/ are allowed. 
           * 
           * Example: vskprintf('y = %y$d, x = %x$1.1f', array('x' => 1, 'y' => 2)) 
           * Result:  'y = 2, x = 1.0' 
           * 
           * $args also can be object, then it's properties are retrieved 
           * using get_object_vars(). 
           * 
           * '%s' without argument name works fine too. Everything vsprintf() can do 
           * is supported. 
           * 
           * @author Josef Kufner <jkufner(at)gmail.com> 
           */ 
          function vksprintf($str, $args) 
          { 
              if (is_object($args)) { 
                  $args = get_object_vars($args); 
              } 
              $map = array_flip(array_keys($args)); 
              $new_str = preg_replace_callback('/(^|[^%])%([a-zA-Z0-9_-]+)\$/', 
                      function($m) use ($map) { return $m[1].'%'.($map[$m[2]] + 1).'$'; }, 
                      $str); 
              return vsprintf($new_str, $args); 
          } 
          ?>

          PHP wordwrap() Function

          What does wordwrap() do?

          The PHP wordwrap() function will wraps a string to a given number of characters.

          PHP wordwrap() Syntax

           wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = FALSE ]]] ) : string

          PHP wordwrap() Parameters

          1. str — The input string.

          2. width — The number of characters at which the string will be wrapped.

          3. break — The line is broken using the optional break parameter.

          4. cut — If the cut is set to TRUE, the string is always wrapped at or before the specified width. So if you have a word that is larger than the given width, it is broken apart. (See second example). When FALSE the function does not split the word even if the width is smaller than the word width.

          PHP wordwrap() Return Value

          The PHP wordwrap() function returns the given string wrapped at the specified length.

          PHP wordwrap() Working Examples

          1. wordwrap() example

          <?php
          $text = "The quick brown fox jumped over the lazy dog.";
          $newtext = wordwrap($text, 20, "<br />\n");
          echo $newtext;
          ?>

          Output of the above code:

          The quick brown fox<br />
          jumped over the lazy<br />
          dog.

          2. wordwrap() example

          <?php
          $text = "A very long woooooooooooord.";
          $newtext = wordwrap($text, 8, "\n", true);
          echo "$newtext\n";
          ?>

          Output of the above code:

          A very
          long
          wooooooo
          ooooord.

          3. wordwrap() example

          <?php
          $text = "A very long woooooooooooooooooord. and something";
          $newtext = wordwrap($text, 8, "\n", false);
          echo "$newtext\n";
          ?>

          Output of the above code:

          A very
          long
          woooooooooooooooooord.
          and
          something

          Additional Tips from Fellow Developers

          Contributed By: ju1ius

          Another solution to utf-8 safe wordwrap, unsing regular expressions.
          Pretty good performance and works in linear time.
          <?php
          function utf8_wordwrap($string, $width=75, $break="\n", $cut=false)
          {
            if($cut) {
              // Match anything 1 to $width chars long followed by whitespace or EOS,
              // otherwise match anything $width chars long
              $search = '/(.{1,'.$width.'})(?:\s|$)|(.{'.$width.'})/uS';
              $replace = '$1$2'.$break;
            } else {
              // Anchor the beginning of the pattern with a lookahead
              // to avoid crazy backtracking when words are longer than $width
              $pattern = '/(?=\s)(.{1,'.$width.'})(?:\s|$)/uS';
              $replace = '$1'.$break;
            }
            return preg_replace($search, $replace, $string);
          }
          ?>
          Of course don't forget to use preg_quote on the $width and $break parameters if they come from untrusted input.

          Contributed By: Dave Lozier – dave

          If you'd like to break long strings of text but avoid breaking html you may find this useful. It seems to be working for me, hope it works for you. Enjoy. :) 
           
          <?php 
              function textWrap($text) { 
                  $new_text = ''; 
                  $text_1 = explode('>',$text); 
                  $sizeof = sizeof($text_1); 
                  for ($i=0; $i<$sizeof; ++$i) { 
                      $text_2 = explode('<',$text_1[$i]); 
                      if (!empty($text_2[0])) { 
                          $new_text .= preg_replace('#([^\n\r .]{25})#i', '\\1  ', $text_2[0]); 
                      } 
                      if (!empty($text_2[1])) { 
                          $new_text .= '<' . $text_2[1] . '>';    
                      } 
                  } 
                  return $new_text; 
              } 
          ?>


          Rate this post —

          Very PoorPoorAverageGoodExcellent (No Ratings Yet)
          Loading...

          Tags: |

          Subscribe
          Notify of
          guest
          0 Comments
          Oldest
          Newest Most Voted
          Inline Feedbacks
          View all comments
          0%