PHP's ability to handle strings is very powerful, and there are a variety of ways, but sometimes you need to choose the simplest and most desirable solution. This article lists 10 common string processing cases in PHP, and provides the most appropriate processing methods.
1. Determine the length of a string
This is the most obvious example of the article, where the question is how we can determine the length of a string, and here we cannot fail to mention the strlen () function:
$text = "Sunny Day"; $count = strlen ($text); $count = 9
2. Truncate the text and create a summary
News-Nature sites usually intercept a paragraph about 200 words, and add ellipses at the end of the paragraph to form a summary, and 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. Calculating the number of characters and words in a string
I believe you will often see some blog or news articles, to summarize the total number of words, or we often see some of the requirements of the submission: within a certain range of words. 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 There are times when you need to have more control over the contributors ' use of 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. Parse the CSV file
The data is usually stored in a comma-delimited file (such as a known CSV file), and the CSV file uses a comma or similar to a predefined symbol to make each column string a separate line. You may often create PHP scripts to import this data, or to parse out what you need, over the years, I have seen many methods of parsing CSV files, most commonly using the combination of fgets () and explode () functions to read and parse files, however, 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. Converting to a string array
At some point, you may need to create a CSV file and read it in these files, which means you need to convert the comma-delimited strings 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 into an array:
$csv = Implode (",", $record);
6. Convert URLs to hyperlinks
Currently, many WYSIWYG editors provide toolbars that allow users to tag text, including hyperlinks. However, when content is rendered to a page, you can easily automate the process and ensure that you do not get any additional errors. To convert a URL to a hyperlink, you can use the Preg_replace () function, which searches for a string by regular expression and defines the structure of the URL:
$url = "Lanfengye, LLC (http://www.9it.me)";
$url = Preg_replace ("/http://([a-z0-9./-]+)/", "$", $url);
$url = "Lanfengye, LLC (http://www.9it.me)"
7. Removing 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, which, if any, can result in SQL injection or scripting attacks. The PHP language contains a number of security features that can help you filter data, including extending filters. For example, you can allow the user to have some basic HTML statements, including some comments. To implement this function, you can use the 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 tags you specify. For example, in the following example, you can remove all the tags:
$text = Strip_tags ($input, "");
8. Comparison of two strings
Compare two strings to make sure they are the same. For example, you can use the Substr_compare () function to make it easy to determine if the user first entered the same password as the second time:
$PSWD = "secret";
$PSWD 2 = "secret";
if (! strcmp ($PSWD, $pswd 2))
{echo "The passwords is not identical!";
If you want to determine that two strings are not case-sensitive, you can use the strcasecmp () function.
9. Convert newline characters
In this article I describe how to easily convert URLs to hyperlinks, and now introduce the NL2BR () function, which can help you convert any newline character into an HTML tag.
$comment = NL2BR ($comment);
10. Apply the Wrap line
Apply word wrap, you can use this function in PHP: WordWrap ():
$speech = "Four score and seven years ago we fathers brought forth,
Upon this continent, a new nation, conceived in Liberty,
and dedicated to the proposition, all men is created equal. ";
Echo WordWrap ($speech, 30); Execute the above code, the result is:
Four score and seven years ago we fathers brought forth, upon this continent, a new nation, conceived in Liberty, and ded Icated to the proposition, all men is created equal.
Addcslashes-adds a backslash escape character for some characters inside a string
addslashes-characters inside a string are escaped in the specified manner
bin2hex-converts binary data to hexadecimal notation
alias function for Chop-rtrim ()
chr-returns the ASCII code of a character
Chunk_split-divide a string into small pieces at a certain length of character
Convert_cyr_string-converting Slavic characters to other characters
convert_uudecode-decrypting a string
convert_uuencode-Encrypt a string
count_chars-returns the character usage information for a string
crc32-computes a crc32 polynomial of a string
crypt-one-way hash encryption function
Echo-used to display some content
Explode-converts a string into an array form with a separator
fprintf-returns data as required and writes directly to the document stream
Get_html_translation_table-returning HTML entities that can be converted
hebrev-converting Hebrew encoded strings to visual text
hebrevc-converting Hebrew encoded strings to visual text
Inverse of the html_entity_decode-htmlentities () function to convert HTML entities to characters
htmlentities-convert some characters in a string to HTML entities
Inverse of the htmlspecialchars_decode-htmlspecialchars () function to convert HTML entities to characters
htmlspecialchars-convert some characters in a string to HTML entities
implode-to convert an array to a string with a specific separator character
join-convert an array to a string, alias of the Implode () function
levenshtein-Calculate the difference size of two words
localeconv-getting a number-related format definition
ltrim-to remove whitespace to the left of a string or to a specified character
md5_file-a file for MD5 algorithm encryption
md5-a string for MD5 algorithm encryption
Metaphone-judging the pronunciation rules of a string
money_format-output of numbers formatted according to parameters
nl_langinfo-querying language and local information
nl2br-Replace the line break "n" in the string with "
”
number_format-output of numbers formatted according to parameters
ord-converts an ASCII code to one character
parse_str-Convert a string of a certain format into a variable and a value
Print-used to output a single value
printf-data Display as required
Quoted_printable_decode-to encrypt a string into a 8-bit binary string
Quotemeta-to escape a number of specific characters
rtrim-remove whitespace to the right of a string or a specified character
setlocale-setting local formats for numbers, dates, and so on
sha1_file-a file for SHA1 algorithm encryption
Sha1-a string for SHA1 algorithm encryption
Similar_text-compares two strings and returns the number of similar characters that the system thinks
Soundex-judging the pronunciation rules of a string
The sprintf-returns the data as required, but does not output
sscanf-can format a string
str_ireplace-matches and replaces strings like the Str_replace () function, but is case insensitive
str_pad-padding on both sides of a string
str_repeat-repeating combinations of strings
str_replace-matching and replacing strings
str_rot13-string for ROT13 encryption processing
str_shuffle-random ordering of characters inside a string
str_split-splits a string into an array by character spacing
str_word_count-get the English word information inside the string
strcasecmp-size comparison of strings, case insensitive
Strchr-the alias of a partial strstr () function that returns a string by comparison
strcmp-size comparison of strings
strcoll– size comparison of strings based on local settings
strcspn-returns the value of a continuous non-matching length of characters
strip_tags-remove HTML and PHP code from a string
stripcslashes-inverse literal addcslashes () function escapes processed strings
Stripos-finds and returns the position of the first occurrence, matching is case-insensitive
stripslashes-inverse literal addslashes () function escapes processed strings
stristr-returns a portion of a string by comparison, case-insensitive compared
Strlen-gets the encoded length of a string
strnatcasecmp-the size comparison of strings using natural sorting, case-insensitive
strnatcmp-the size comparison of strings using the natural sort method
strncasecmp-size comparison of the first n characters of a string, case insensitive
strncmp-size comparison of the first n characters of a string
strpbrk-returns a portion of a string by comparison
strpos-Find and return the position of the first occurrence
strrchr-returns a part of a string by comparing it from backward to forward
strrev-all letters inside the string in reverse order
Strripos-finds and returns the position of the first match from the back, matching is case insensitive
strrpos– Find and return the position of the first match from behind
strspn-matches and returns the value of the character continuous occurrence length
strstr-returns a portion of a string by comparison
strtok-to split a string with a specified number of characters
strtolower-converting a string to lowercase
strtoupper– converting a string to uppercase
strtr-to string comparison substitution
Substr_compare-Comparison of strings after interception
substr_count-count occurrences of a character segment in a string
substr_replace-to replace part of a character in a string
substr-to intercept a string
trim-remove whitespace or specified characters on either side of a string
Ucfirst-converts the first letter of a given string to uppercase
ucwords-the first letter of each English word of the given string into uppercase
vfprintf-returns data as required and writes directly to the document stream
vprintf-data Display as required
The vsprintf-returns the data as required, but does not output
wordwrap-to divide a string by a certain character length
http://www.bkjia.com/PHPjc/445622.html www.bkjia.com true http://www.bkjia.com/PHPjc/445622.html techarticle PHP's ability to handle strings is very powerful, and there are a variety of ways, but sometimes you need to choose the simplest and most desirable solution. The article lists 10 common strings in PHP ...