PHP Learning Series (1) & mdash; string processing functions (4), php Functions

Source: Internet
Author: User
Tags chop crc32 first string key string md5 hash

PHP Learning Series (1) -- string processing functions (4), php Functions

16. The hebrevc () function switches the flow of Hebrew text from right to left to the flow from left to right. It also converts the new line (\ n) to <br/>. Only ASCII characters between 224 and 251 are affected.

Syntax: hebrev (string, maxcharline)
Maxcharline specifies the maximum number of characters in each line. If possible, hebrev () will avoid breaking words. Tip: hebrev () and hebrevc () can convert the Hebrew logical text to the Hebrew visible text. Hebrew visible text does not require special support for right-to-left characters, which makes it useful for displaying Hebrew text on the web.

17. The htmlspecialchars () function converts some predefined characters into HTML objects.

The predefined characters are:

  • & (And number) becomes & amp;
  • "(Double quotation marks) into & quot;
  • '(Single quotes) becomes & #039;
  • <(Less than) to become <;
  • > (Greater than) to become & gt;
Syntax: htmlspecialchars (string, quotestyle, character-set)

Quotestyle -- Optional. Specifies how to encode single quotes and double quotes.

  • ENT_COMPAT-default. Only double quotation marks are encoded.
  • ENT_QUOTES-encode double quotation marks and single quotation marks.
  • ENT_NOQUOTES-do not encode any quotation marks.

Character-set -- Optional. String value that specifies the character set to be used.

  • ISO-8859-1-default. Western Europe.
  • ISO-8859-15-Western Europe (with the Euro symbol and letters in French and Finnish ).
  • UTF-8-ASCII compatible multi-byte 8-bit Unicode
  • Cp866-DOS dedicated Cyrillic character set
  • Cp1251-Windows dedicated Cyrillic character set
  • Cp1252-Western European character set for Windows
  • KOI8-R-Russian
  • GB2312-Simplified Chinese, National Standard Character Set
  • BIG5-Traditional Chinese
  • BIG5-HKSCS-Big5 Hong Kong Extension
  • Shift_JIS-Japanese
  • EUC-JP-Japanese
Tip: Unrecognized character sets will be ignored and replaced by a ISO-8859-1. Example

Browser output:

John & 'Adams'John & 'Adams'John & 'Adams'

If you view the source code in the browser, you will see the following HTML:

 

18. The htmlspecialchars_decode () function converts some predefined HTML entities into characters, which is the inverse function of htmlspecialchars.

Syntax: htmlspecialchars_decode (string, quotestyle)

The meanings of quotestyle are the same as those of htmlspecialchars ().

19. The implode () function combines array elements into a string.

Syntax: implode (separator, array)
Separator -- Optional. Specifies the content to be placed between array elements. The default value is "" (Null String ).

Array -- required. Array to be combined as a string.

Note: Although SeparatorThe parameter is optional. However, we recommend that you use two parameters for backward compatibility. Note: implode () can receive two parameter sequences. However, explode () cannot be used for historical reasons. You must ensure SeparatorParameters in StringBefore the parameter. Example
<?php$arr = array('Hello','World!','Beautiful','Day!');echo implode(" ",$arr);?>

Output:

Hello World! Beautiful Day!
20. The join () function combines array elements into a string. The join () function is the alias of the implode () function.
21. The levenshtein () function returns the Levenshtein distance between two strings.

Levenshtein distance, also known as the editing distance, refers to the minimum number of edits required to convert a string from one to another. Licensed editing operations include replacing one character with another, inserting one character, and deleting one character.

For example, convert kitten to sitting:

The levenshtein () function gives each operation the same weight (replacement, insertion, and deletion. However, you can set optional insert, replace, and delete parameters to define the cost of each operation.

Syntax: levenshtein (string1, string2, insert, replace, delete)
Parameters Description
String1 Required. The first string to be compared.
String2 Required. The second string to be compared.
Insert Optional. The cost of inserting a character. The default value is 1.
Replace Optional. The cost of replacing a character. The default value is 1.
Delete Optional. The cost of deleting a character. The default value is 1.

Note:

If one of the strings exceeds 255 characters, the levenshtein () function returns-1. The levenshtein () function is case insensitive. The levenshtein () function is faster than the similar_text () function. However, the similar_text () function provides more accurate results that require less modification.

Example
<?phpecho levenshtein("Hello World","ello World");echo "<br />";echo levenshtein("Hello World","ello World",10,20,30);?>

Output:

130
22. The localeconv () function returns an array containing local numbers and currency information formats.
23. The ltrim () function removes spaces or other predefined characters from the left side of the string. Functions are similar to chop () or rtrim ();
24. md5 hash of the string calculated by the MD5 () function. The md5 () function uses RSA Data Security, including the MD5 packet excerpt algorithm. If the calculation succeeds, the calculated MD5 hash is returned. If the calculation fails, false is returned.
Syntax: md5 ( String, Raw)

Raw --Optional. The hexadecimal or binary output format is required:

  • TRUE-original 16-character binary format
  • FALSE-default. 32-character hexadecimal number

Note: this parameter is added in PHP 5.0.

25. MD5 hash of the md5_file () function compute file. The md5 () function uses RSA Data Security, including the MD5 packet excerpt algorithm. If the calculation succeeds, the calculated MD5 hash is returned. If the calculation fails, false is returned.

Example 1
<?php$filename = "test.txt";$md5file = md5_file($filename);echo $md5file;?>

Output:

5d41402abc4b2a76b9719d911017c592
26. metaphone () function calculates the metaphone key of the string. English pronunciation of metaphone key string. Metaphone () function can be used for spelling check applications.
If the call succeeds, the metaphone key of the string is returned. If the call fails, false is returned.
Syntax: metaphone (string, length)

Length -- Optional. Specifies the maximum length of the metaphone key. Note: metaphone () creates the same key for words with similar pronunciation. The length of the generated metaphone key is variable. Metaphone () is more accurate than soundex (), because metaphone () understands Basic English pronunciation rules. Example: Example 1

<?phpecho metaphone("world");?>

Output:

WRLT
Example 2

In this example, we apply the metaphone () function to two words with similar pronunciation:

<?php$str = "Sun";$str2 = "Son";echo metaphone($str);echo metaphone($str2);?>

Output:

SNSN
27. The money_format () function formats the string as a currency string.
Syntax: money_format (string, number)
Number -- Optional. The number at the position of % in the inserted formatted string. Note: The money_format () function cannot work on windows. Example: Example 1

International en_US format:

<?php$number = 1234.56;setlocale(LC_MONETARY, "en_US");echo money_format("The price is %i", $number);?>

Output:

The price is USD 1,234.56
Example 2

Negative number. The US International format with () indicates a negative number. The precision on the right side is 2. "*" is a filling character:

<?php$number = -1234.5672;echo money_format("%=*(#10.2n", $number);?>

Output:

($********1,234.57)
28. The nl_langinfo () function returns the specified local information.

If yes, the specified local information is returned. If it fails, false is returned. Syntax: nl_langinfo (element)

Element -- required. Specifies the element to return. Must be one of the elements listed in the description. Note:

Time and calendar:

  • ABDAY _ (1-7)-Abbreviated name of the numbered day of the week
  • DAY _ (1-7)-Name of the numbered day of the week (DAY_1 = Sunday)
  • ABMON _ (1-12)-Abbreviated name of the numbered month of the year
  • MON _ (1-12)-Name of the numbered month of the year
  • AM_STR-String for Ante meridian
  • PM_STR-String for Post meridian
  • D_T_FMT-String that can be used as the format string for strftime () to represent time and date
  • D_FMT-String that can be used as the format string for strftime () to represent date
  • T_FMT-String that can be used as the format string for strftime () to represent time
  • T_FMT_AMPM-String that can be used as the format string for strftime () to represent time in 12-hour format with ante/post meridian
  • ERA-Alternate era
  • ERA_YEAR-Year in alternate era format
  • ERA_D_T_FMT-Date and time in alternate era format (string can be used in strftime ())
  • ERA_D_FMT-Date in alternate era format (string can be used in strftime ())
  • ERA_T_FMT-Time in alternate era format (string can be used in strftime ())

Currency type:

  • INT_CURR_SYMBOL-Currency symbol (example: USD)
  • CURRENCY_SYMBOL-Currency symbol (example: $)
  • CRNCYSTR-Same as CURRENCY_SYMBOL
  • MON_DECIMAL_POINT-Monetary decimal point character
  • MON_THOUSANDS_SEP-Monetary thousands separator
  • POSITIVE_SIGN-Positive value character
  • NEGATIVE_SIGN-Negative value character
  • MON_GROUPING-Array displaying how monetary numbers are grouped (example: 1 000 000)
  • INT_FRAC_DIGITS-International fractional digits
  • FRAC_DIGITS-Local fractional digits
  • P_CS_PRECEDES-True (1) if currency symbol is placed in front of a positive value, False (0) if it is placed behind
  • P_SEP_BY_SPACE-True (1) if there is a spaces between the currency symbol and a positive value, False (0) otherwise
  • N_CS_PRECEDES-True (1) if currency symbol is placed in front of a negative value, False (0) if it is placed behind
  • N_SEP_BY_SPACE-True (1) if there is a spaces between the currency symbol and a negative value, False (0) otherwise
  • P_SIGN_POSN-Formatting setting. Possible return values:
    • 0-Parentheses surround the quantity and currency symbol
    • 1-The sign string is placed in front of the quantity and currency symbol
    • 2-The sign string is placed after the quantity and currency symbol
    • 3-The sign string is placed immediately in front of the currency symbol
    • 4-The sign string is placed immediately after the currency symbol
  • N_SIGN_POSN-Formatting setting. Possible return values:
    • 0-Parentheses surround the quantity and currency symbol
    • 1-The sign string is placed in front of the quantity and currency symbol
    • 2-The sign string is placed after the quantity and currency symbol
    • 3-The sign string is placed immediately in front of the currency symbol
    • 4-The sign string is placed immediately after the currency symbol

Number category:

  • DECIMAL_POINT-Decimal point character
  • RADIXCHAR-Same as DECIMAL_POINT
  • THOUSANDS_SEP-Separator character for thousands
  • THOUSEP-Same as THOUSANDS_SEP
  • GROUPING-Array displaying how numbers are grouped (example: 1 000 000)

Communication type:

  • YESEXPR-Regex string for matching 'yes' input
  • NOEXPR-Regex string for matching 'no' input
  • YESSTR-Output string for 'yes'
  • NOSTR-Output string for 'no'

Code set category:

  • CODESET Return a string with the name of the character encoding.
Tips and comments

Note: The money_format () function cannot work on windows.

Tip: Unlike the localeconv () function that returns all local formatting information, nl_langinfo () returns the specified information.

29. The nl2br () function inserts an HTML Line Break (<br/>) before each new line (\ n) in the string ).

Syntax: nl2br (string)
<?phpecho nl2br("One line.\nAnother line.");?>

Output:

One line.Another line.

HTML code:

One line.<br />Another line.
30. The number_format () function uses a thousand-bit grouping to format numbers. Syntax: number_format (number, decimals, decimalpoint, separator)

Number -- required. The number to be formatted. If no other parameter is set, the number is formatted as a comma (,) without a decimal point.

Decimals -- Optional. Specifies the number of decimal places. If this parameter is set, the period (.) is used as the decimal point to format the number.

Decimalpoint -- Optional. Specifies the string used as the decimal point.

Separator -- Optional. A string that is required to be used as a thousands separator. Use only the first character of this parameter. For example, "xyz" only outputs "x ". Note: If this parameter is set, all other parameters are required. Note: This function supports one, two, or four parameters (not three ). Example

<?phpecho number_format("1000000");echo number_format("1000000",2);echo number_format("1000000",2,",",".");?>

Output:

1,000,0001,000,000.001.000.000,00
 

How does php handle strings?

Through learning PHP, you can use this advanced language to create a website with high performance. For beginners, the PHP string mbstring is still relatively unfamiliar. Next we will introduce the specific application of the PHP string mbstring.

Multi-language coexistence means Multi-byte. the built-in String Length function strlen in PHP cannot correctly process Chinese strings, and only obtains the number of bytes occupied by strings. For GB2312 Chinese encoding, The strlen value is twice the number of Chinese characters, and for the UTF-8 encoding of Chinese, is 1 ~ 3 times the difference.

Using the PHP string mbstring can better solve this problem. The usage of mb_strlen is similar to that of strlen, except that it has a second optional parameter for specifying character encoding. For example, to get the length of the string $ str for the UTF-8, you can use mb_strlen ($ str, 'utf-8 ′). If the second parameter is omitted, the internal code of PHP is used. The internal encoding can be obtained through the mb_internal_encoding () function. There are two ways to set the internal encoding:

1. Set mbstring. internal_encoding = UTF-8 in php. ini

2. Call mb_internal_encoding ("GBK ")

In addition to the PHP string mbstring, there are many cutting functions, in which mb_substr is used to split characters by words, while mb_strcut is used to split characters by bytes, but no half character is generated. In addition, function cutting has different effects on the length. The cut condition of mb_strcut is smaller than strlen, and that of mb_substr is equal to strlen. See the example below,

<? $ Str = 'I am a long string of Chinese characters -www.jefflei.com'; echo "mb_substr :". mb_substr ($ str, 0, 6, 'utf-8'); echo ""; echo "mb_strcut :". mb_strcut ($ str, 0, 6, 'utf-8');?>

The output is as follows:

Mb_substr: I am a comparison string

Mb_strcut: I am

Note that the PHP string mbstring is not the core function of PHP. before using the function, make sure that the mbstring support is added to the php compilation module:

(1) Use-enable-mbstring during compilation

(2) Modify/usr/local/lib/php. inc

Default_charset = "zh-cn"

Mbstring. language = zh-cn

Mbstring. internal_encoding = zh-cn

The PHP string mbstring class library contains a lot of content. It also includes e-mail processing functions such as mb _ send _ mail.

(100 points) [php] write several familiar string processing functions!

Addcslashes addslashes bin2hex chop chr chunk_split convert_cyr_string cyrillic
Convert_uudecode convert_uuencode count_chars crc32 crc32 crypt echo explode

Fprintf get_html_translation_table hebrev

Hebrevc
Hex2bin-Decodes a hexadecimally encoded binary string
Html_entity_decode-Convert all HTML entities to their applicable 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

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
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

Number_format-Format a number with grouped thousands
Ord

Parse_str

Print

Printf

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
Setlocale-Set locale information
Sha1_file

Sha1

Soundex-Calculate the soundex key of a string
Sprintf-Return a formatted string
Sscanf-Parses input from a string according to a ...... the remaining full text>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.