PHP Processing string Tips Small summary

Source: Internet
Author: User
Tags comparison explode first string html tags php language sql injection strcmp strlen

String is a piece of cake, I summarize some common processing string functions.

1. Determine the length of a string

This is one of the most obvious examples of the article, the question is how we can determine the length of a string, and here we have to mention the strlen () function:
$text = "Sunny Day";

$count = strlen ($text);

$count = 9

2. Intercept text, create a summary

A news site usually intercepts a paragraph about 200 words and appends an ellipsis to the end of the second paragraph to form a summary, at which point you can use the Substr_replace () function to implement this function. For space reasons, only the 40-character limit is shown 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 a string

I believe you will often see some blog or news articles, to sum up the total number of words, or we often see some of the requirements of the submission: within a certain amount of word range. At this point, you can use the Str_word_count () function to calculate the sum of the words in the article:

$article = "Breaking NEWS:

In Ultimate irony, man bites dog. ";

$wordCount = Str_word_count ($article);

$wordCount = 8

Sometimes you need to be more disciplined about the use of the contributors ' space, such as some annotations and so on. If you want to know how many characters make up an array, use the Count_chars () function.

4. csv file resolution

Data is usually stored in a comma-delimited form in a file (such as a known CSV file), and a CSV file uses a comma or similar to a predefined symbol to make each column string a separate row. You can often create PHP scripts to import this data, or parse out what you need, and over the years, I've seen many ways to parse CSV files, most commonly using a combination of fgets () and explode () functions to read and parse files, but The simplest approach is to use a function to solve the problem, but it is not part of the PHP string processing library: the Fgetcsv () function. Using the fopen () and Fgetcsv () functions, we can easily parse the file and retrieve the name of each contact:

$fh = fopen ("Contacts.csv", "R");

while ($line = Fgetcsv ($fh, 1000, ","))

{echo "contact: {$line [1]}";

}

5. Convert to an array of strings

At some point, you might want to create a CSV file and read it in these files, which means you need to convert those strings separated by commas into data. If the data was originally retrieved from the database, it is likely that it will only provide you with an array. At this point, you can use the implode () function to convert these strings to an array:

$csv = Implode (",", $record);

6. Convert the URL into a hyperlink

Many WYSIWYG editors currently offer toolbars that allow users to tag text, including hyperlinks. However, when content is rendered on the page, you can easily automate this process while ensuring that you do not have additional errors. To convert to a hyperlink URL, you can use the Preg_replace () function, which searches for a string according to the regular expression and defines the structure of the URL:

$url = "W.J Gilmore, LLC (http://www.wjgilmore.com)";

$url = Preg_replace ("//([a-z0-9./-]+)/", "$", $url);

$url = "W.J Gilmore, LLC"

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 dangerous characters, and if so, this can lead to SQL injection or script attacks. The PHP language contains a number of security features that can help you filter data, including extending the filter. For example, you can allow users to have some basic HTML statements, including some comments. To implement this function, you can use a function with check function: Strip_tags (). It removes all HTML tags from the string by default, but it also allows you to override the default or the label you specify. For example, in the following example, you can remove all the tags:

$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 a user's first password is the same as the second entered, which is an easy reality:

$PSWD = "secret";

$PSWD 2 = "secret";

If

(! strcmp ($PSWD, $pswd 2))

{echo "The passwords are not identical!";

}

If you want to judge that two strings are case-insensitive, you can use the strcasecmp () function.

9. Convert line break

In this article I introduced how to easily convert URLs to hyperlinks, now introduce the NL2BR () function, which can help you convert any line break into an HTML tag.

$comment = NL2BR ($comment);

10. Apply Automatic line Wrapping

To apply word wrapping, you can use this function in PHP: WordWrap ():

$speech = "Four score and seven years ago our fathers brought,

Upon this continent, a new nation,

Conceived in Liberty,

and dedicated to the proposition, all men are created equal. ";

Echo WordWrap ($speech, 30);

Execute the above code, and the result is:

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


1. Stitching string
Stitching string is one of the most commonly used string operations, in PHP, three ways to support the concatenation of strings, respectively, is a dot. The delimiter {} operation, and the dot equals sign. = To do the operation, the dot equals sign can decompose a relatively long string into several lines to define, which is more beneficial.

2. Replacement string
In the language of PHP, a function named Substr_replace () is provided, which can quickly scan and edit the string substitution function of the text content. His grammatical format: mixed substr_replace (mixed $string, string $replacement, int $start, [int $length])

3. Compute string
Calculates the length of a string: in PHP, the strlen () function is used to compute the length of a string and to return the length information of that string. The syntax is formatted as follows: the string in the int strlen (string $string) format is used to specify the strings to calculate the length.

Number of calculated strings: in PHP, the Substr_count () function, which can be used very conveniently and accurately to determine how many of a given substring is in the supplied string, has the following syntax format for the Substr_count () function: int Substr_count ( String $haystack, String $needle [, int $offset =0[,int $length]]) The parameters designed in the syntax above are described as follows: haystack specifies the string to be checked, Needle is used to specify the string to insert, offset is used to specify where to start the search in the string, and the default value is 0,length to specify the length of the search.

In PHP, the Str_word_count () function can be used to easily and accurately determine how many words a word has in the supplied string, and the syntax format of the Str_word_count () function is as follows: Mixed Str_word_count ( string $string [, int $format =0[,string $charlist]] The arguments that are involved in the syntax above are described as follows: string specifies the string to be checked, and format is used to specify Str_word_count () The return value of the function, which returns a value of three values, namely 0,1,2. Where return 0 means the default value, returns the number of words found, and if the return value is 1, then Str_word_count () returns an array in which the key name is a sequential integer starting from 0, and the value is the actual word. If the value of format is 3, then the return value of the Str_word_count () function is an array in which the key name of the array is the position of the word in the string, and the value is the actual word.

4. Find string
The search for strings can be divided into a number of ways, such as finding substrings, finding the location of a string, and so on, and PHP provides the corresponding function for each string lookup operation.

Lookup substring: In the PHP language, the STRSTR () function can be used to find a substring that returns the result of all the contents of the first occurrence of the substring, and the strstr () function is formatted as follows: String Strstr (String $haystack, Mixed $needle) in the above syntax, the parameters involved are described below haystack: Specifies the searched string, needle specifies the string to search for, and if the argument is a number, it matches the character of the numeric ASCII value. In the actual application, there will be to ignore the letter case, this time, you can use PHP provided a case insensitive lookup function--stristr () function, the use of the function and the STRSTR () function is the same.

Find the location of the string: The function of the Strpos () function is similar to the STRSTR () function, but instead of returning a string, the first occurrence of a string in another string, Strpos () has the following syntax format: int Strpos (String $ Haystack,mixed $needle [, int $offset = 0]) The arguments involved in the above syntax are described as follows: Haystack is the string to be searched, needle Specifies the string to find, and offset is the location where the search is to begin. The default value is 0.

The Strpos () function is a case sensitive lookup function, but in the actual application process there will often be a need to ignore the case, this time you can use a PHP provided by the case is not very sensitive lookup function Stripos (), the function of the use of methods and Strpos () is the same.

5. Comparing strings
In the PHP language, comparing the size of two strings can be done in two ways: using the "= =" operator to compare and use functions for comparison

Use the "= =" operator to compare the size of two strings: the easiest way to compare two strings in PHP is to use the double equals operator (= =).

Use a function to compare the size of a string: the strcmp () function provided in PHP provides a more accurate comparison of the size of two strings, with the following syntax format int strcmp (string $str 1,string $str 2) The parameters involved in the above syntax are described as follows: str1 specifies the string to be compared 1,STR2 specifies the string 2 to be compared. This strcmp is well versed in ensuring that two strings match exactly and returns the comparison as an integer, with the following three types of return values for this function. 0: Two strings are equal, less than 0, the first string is less than the following string, if the return value is greater than 0, then the previous string is greater than the later string.

In addition to the strcmp () function, PHP provides other comparable comparison functions, such as the strncmp () function to select the length of the string you want to compare (the number of characters), the syntax is as follows: int strcmp (string $str 1,string $ Str2,int $len) Description str1: Specifies the first string to compare, str2: Specifies the second string len to compare: Specifies the number of characters each string is used for comparison.

When comparing strings, sometimes you need to ignore the case, you can use the Strcasemp () function and the strncasemp () function, which is exactly the same as the use of case-sensitive corresponding functions, strcasecmp () functions and STRNCASECMP () The syntax format of the two functions is as follows:

int strcasecmp (String $str 1,string $str 2)

int strncasecmp (string $str 1,string $str 2,int $len)

6. Copy string
If you need to repeat the function of a character or a string, the simplest way to do this is to invoke the copy function, which in PHP can be used to replicate the string using the Str_repeat () function, which has the following syntax format: String Str_repeat (String $input, int $multiplier) Description of the parameters designed in the syntax described below specifies the string to repeat, multiplier the number of times the specified string will be repeated.

7. Flip String
Manipulating strings also includes flipping strings in the PHP language, you can use the Strrev () function to reverse the function of a string, the syntax format of the Strrev () function is String Strrev (string $string)

The argument string above is used to specify the string to flip.

8. Splitting, merging strings
Splitting a string into multiple strings according to a rule, or merging multiple strings into a long string, is a frequent problem when dealing with string operations. Using the explode () function provided by PHP, the Str_split () function, the implode () function can handle problems like splitting and merging strings.

Shard String: The function of the explode () function is to cut the string into an array with the specified delimiter, and the syntax format of the explode () function is as follows: Array explode (string $delimiter, string $string [, int $ Limit] The arguments involved in the above syntax are described as follows: delimiter: Specifies where to delimit the string, string: Specifies the string to be split, limit: Specifies the maximum number of array elements returned, and the last child block will contain the remainder of the string.

The Str_split () function is the ability to split a string into multiple substrings of equal length. The syntax for the Str_split () function is as follows: The arguments in the syntax above for array str_split (string $string [, int $split _length=1]) are described as follows: string: Specifies the string to be split, Split_ Length: Specifies the lengths of each array element, and the default value is "1".

Merging strings: The function of the implode () function is to concatenate the elements of an array into strings, and the syntax of the implode () function is as follows: String implode ([string $glue],array $pieces) The parameters involved in the above syntax are described as follows: Glue () Specifies what is placed between array elements, and the default value is "" (for a space string) pieces specifies the array to be merged into a string. Call the implode () function to get a new string that can be used to merge strings based on conditions that are restricted by the parameters.

Join () is the alias of the Implode () function, and the use of two functions is exactly the same, and it should be emphasized that although parameter glue is optional, two parameters are recommended for better compatibility of the program

Summary of how strings are related:

1.printf () Function: strings can be formatted for operation
2.sprintf () function: You can format a string, and the difference between the printf () function is that you need to use Echo to display the formatted string as output.
3.NL2BR () function: You can convert the newline character "n" in the string to HTML.
"After showing it.
4.wordwrap () function: Specifies a newline from a column character
5.strtolower () Function: This function implements the function of converting all characters in a string into lowercase letters
6.strtoupper () function: The function is to convert all characters in a string to uppercase characters
7.ucwords () function: The function is to convert all the first characters in the string to uppercase letters
8.substr_replace () function: the ability to quickly scan and edit strings with more text content
9.strlen () function: You can calculate the length of a string and return the length of the string
10.substr_count () function: You can determine how many of the strings in the supplied string
11.str_word_count () function to determine the number of occurrences of a word in a string.
The 12.strstr () function, which can be used to find a substring that returns the result of all the contents of the substring after the first occurrence of the string
The 13.strpos () function, the function and the STRSTR () function are similar, but instead of returning a string, it is the position of the first occurrence of a string in another string.
14.STRCMP () function, which functions to accurately compare the size of two strings
15.STRNCMP () function, you can select the length of the string to compare (number of characters)
16.STRCASECMP () function, you can compare two strings when ignoring the case
The 17.strncasecmp () function, which allows you to compare the length or number of characters to two strings when you ignore the case.
18.str_repeat () function, repeat n times the function of a character or string
19.strrev () function, which provides an operation to flip a string
The 20.explode () function, which provides the ability to cut a string into multiple strings, specifies the delimiter string to be divided into arrays.
21.str_split () function, which splits a string into multiple substrings of equal length
22.implode () function to concatenate the elements of an array into a string
The 23.join () function, which is the same as the implode () function, is also used to connect the elements of an array into a string

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.