Php string processing functions-PHP Tutorial-php Tutorial

Source: Internet
Author: User
Tags crc32 rtrim
Php string processing functions. PHP can process strings in a variety of ways, but sometimes you need to select the simplest and ideal solution. The article lists 10 common PHP strings. PHP has very powerful processing capabilities and diverse methods, but sometimes you need to choose the simplest and ideal solution. This article lists 10 common cases of string processing in PHP and provides the most ideal processing method.

1. determine the length of a string

This is the most obvious example in the article. The question here is how to determine the length of a string. what we cannot but mention here is the strlen () function:

$ Text = "sunny day"; $ count = strlen ($ text); // $ count = 9


2. extract text and create a summary

News websites usually take a section about 200 characters and add a ellipsis at the end of the section to form a summary. in this case, you can use substr_replace () function. Due to the length of the article, only the limit of 40 characters is demonstrated here:

$ Article = "breaking news: In ultimate irony, man bites dog .";
$ Summary = substr_replace ($ article, "...", 40 );
// $ Summary = "breaking news: In ultimate irony, man bi..." 3. calculate the number of characters and words In the string.


I believe that you will often see blog or news articles to summarize the total number of words in the article, or we often see some requirements for contribution: within a certain word range. In this case, you can use the str_word_count () function to calculate the total number of words in the article:

$ Article = "breaking news: In ultimate irony, man bites dog .";
$ WordCount = str_word_count ($ article); // $ wordCount = 8 sometimes you need to strictly control the space used by contributors, such as comments. If you want to know the number of characters to form an array, use the count_chars () function.

4. parse CSV files

Data is usually stored in a file (such as a known CSV file) in a comma separated form. the CSV file uses a comma or is similar to a predefined symbol, separate each column of strings into a single row. You may often create PHP scripts to import the data or parse what you need. over the years, I have seen many methods to parse CSV files, the most common is to use a combination of fgets () and explode () functions to read and parse files. However, the simplest way is to use a function to solve the problem, but it is not part of the PHP string processing library: fgetcsv () function. Using the fopen () and fgetcsv () functions, we can easily parse this file and retrieve the name of each contact at the same time:

$ Fh = fopen ("contacts.csv", "r ");
While ($ line = fgetcsv ($ fh, 1000 ,","))
{Echo "Contact: {$ line [1]}";}


5. convert to a string array


In some cases, you may need to create CSV files and read them at the same time, which means you need to convert the strings separated by commas into data. If the data is first retrieved from the database, it may only provide you with an array. In this case, you can use the implode () function to convert these strings into an array:

$ Csv = implode (",", $ record );


6. convert the URL to a hyperlink


Currently, many WYSIWYG editors provide toolbar that allow users to mark text, including hyperlinks. However, when the content is displayed on the page, you can easily perform this process automatically without any additional errors. To convert a URL to a hyperlink, you can use the preg_replace () function to search for a string based on a regular expression and define the URL structure:

$ Url = "LanFengye, LLC (http://www.9it.me )";
$ Url = preg_replace ("/http: // ([A-z0-9 ../-] +)/", "$0", $ url );
// $ Url = "LanFengye, LLC (http://www.9it.me )"


7. remove HTML tags from a string


As a Web developer, one of the main tasks is to ensure that user input does not contain any dangerous characters. if so, this will lead to SQL injection or script attacks. PHP includes many security features that help you filter data, including extended filters. For example, you can allow users to include some basic HTML statements, including some annotations. To implement this function, you can use the function strip_tags () with the check function (). By default, it deletes all HTML tags from the string, but it also allows to overwrite the default or tag you specified. For example, in the following example, you can remove all labels:

$ Text = strip_tags ($ input ,"");


8. compare two strings


Compare two strings to make sure they are the same. For example, you can use the substr_compare () function to determine whether the password you entered is the same for the first and second times:

$ Pswd = "secret ";
$ Pswd2 = "secret ";
If (! Strcmp ($ pswd, $ pswd2 ))
{Echo "The passwords are not identical! ";
} If you want to judge whether two strings are case-insensitive, you can use the strcasecmp () function.

9. line feed conversion


This article describes how to easily convert a URL to a hyperlink. now we will introduce the nl2br () function, which can help you convert any line break into an HTML tag.

$ Comment = nl2br ($ comment );


10. automatic application line feed


Automatically wrap the application. you can use this function in PHP: wordwrap ():

$ Speech = "Four score and seven years ago our fathers brought forth,
Upon this continent, a new nation, conceived in Liberty,
And dedicated to the proposition that all men are created equal .";

Echo wordwrap ($ speech, 30); execute the above code and the result is:

Four score and seven years ago our fathers brought forth, upon this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.

Addcslashes-add backslash escape characters to some characters in the string
Addslashes-escape characters in the string in the specified method
Bin2hex-Convert binary data to hexadecimal representation
Alias function of chop-rtrim ()
Chr-returns the ASCII code of a character.
Chunk_split-splits a string into small parts based on a certain character length
Convert_cyr_string-converts a Slavic character to another character
Convert_uudecode-decrypts a string
Convert_uuencode-encrypt a string
Count_chars-returns the character usage information in a string.
Crc32-calculate the crc32 polynomial of a string
Crypt-one-way hash encryption function
Echo-used to display some content
Explode-convert a string into an array using a delimiter
Fprintf-return data as required and directly write data to the document stream
Get_html_translation_table-returns the HTML entity that can be converted.
Hebrev-converts a Hebrew-encoded string to a visualized text
Hebrevc-convert Hebrew-encoded strings into visualized text
The inverse function of the html_entity_decode-htmlentities () function, which converts an HTML object to a character.
Htmlentities-convert some characters in a string to HTML entities
The inverse function of the htmlspecialchars_decode-htmlspecialchars () function, which converts an HTML object to a character.
Htmlspecialchars-convert some characters in a string to HTML entities
Implode-convert an array into a string using a specific delimiter
Join-convert an array into a string, alias of the implode () function
Levenshtein-calculate the differences between two words
Localeconv-get format definitions related to numbers
Ltrim-removes white spaces or specified characters on the left of the string
Md5_file-encrypt an object using the MD5 algorithm
Md5-encrypt a string using the MD5 algorithm
Metaphone-rules for determining the pronunciation of a string
Money_format-formatted output of numbers based on parameters
Nl_langinfo-query language and local information
Nl2br-replace the linefeed "n" in the string with "n"
"
Number_format-formatted output of numbers based on parameters
Ord-converts an ASCII code to a character
Parse_str-convert strings of certain formats into variables and values
Print-Used to output a separate value
Printf-display data as required
Quoted_printable_decode-encrypt a string into an 8-bit binary string
Quotemeta-escape certain characters
Rtrim-removes spaces or specified characters on the right of the string
Setlocale-set the local format of numbers, dates, and so on
Sha1_file-encrypt a file using the SHA1 algorithm
Sha1-encrypt a string using the SHA1 algorithm
Similar_text-compares two strings and returns the number of similar characters that the system considers.
Soundex-rules for determining the pronunciation of a string
Sprintf-return data as required, but do not output
Sscanf-you can format strings.
Str_ireplace-match and replace strings like the str_replace () function, but not case sensitive
Str_pad-pad both sides of the string
Str_repeat-repeated string combination
Str_replace-match and replace strings
Str_rot13-encrypt the string with ROT13
Str_shuffle-random sorting of characters in a string
Str_split-splits a string into an array based on the character spacing
Str_word_count-get the English word information in the string
Strcasecmp-compare the string size, case insensitive
Strchr-returns the alias of some strstr () functions of a string through comparison
Strcmp-compare the string size
Strcoll-compare the string size based on local settings
Strcspn-returns the value of consecutive non-matching lengths.
Strip_tags-remove HTML and PHP code from a string
Stripcslashes-returns the string processed by the addcslashes () function escape function.
Stripos-locate and return the position of the first matching item. the matching is case insensitive.
Stripslashes-returns the string that has been escaped by the implicit addslashes () function.
Stristr-returns the part of a string through comparison. the comparison is case insensitive.
Strlen-get the encoding length of a string
Strnatcasecmp-use the natural sorting method to compare the string size, case insensitive
Strnatcmp-use the natural sorting method to compare the string size
Strncasecmp-compare the size of the first N characters of a string, case insensitive
Strncmp-compare the size of the first N characters of a string
Strpbrk-returns the part of a string through comparison
Strpos-locate and return the position of the first matching item
Strrchr-returns the part of a string through comparison from the back to the back
Strrev-reverse sort all letters in the string
Strripos-search from the back and return the position of the first matching item. the matching is case insensitive.
Strrpos-search from the back and return the position of the first matching item
Strsps-matched and returned continuous length of characters
Strstr-returns the part of a string through comparison
Strtok-use a specified number of characters to separate strings
Strtolower-convert string to lowercase
Strtoupper-converts a string to uppercase
Strtr-replace string comparison
Substr_compare-comparison after string truncation
Substr_count-calculates the number of occurrences of a character segment in a string
Substr_replace-replace some characters in the string
Substr-truncates a string
Trim-removes spaces or specified characters on both sides of the string
Ucfirst-converts the first letter of the given string into uppercase letters.
Ucwords-converts the first letter of each English word of the given string into uppercase letters.
Vfprintf-return data as required and directly write data to the document stream
Vprintf-display data as required
Vsprintf-return data as required, but no output
Wordwrap-splits a string based on a certain character length


Bytes. The article lists 10 common PHP strings...

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.