PHP’s ability to process strings is very powerful, and its methods are diverse, but sometimes you need to choose the simplest and ideal solution. The article lists 10 common string processing cases in PHP and provides The corresponding most ideal processing method.
1. Determine the length of a string
This is the most obvious example in the article. The question is how do we determine the length of a string? We cannot but mention it here The function is strlen():
$text = "sunny day"; $count = strlen($text); // $count = 9
2. Intercept the text and create a summary.
News websites usually A paragraph of about 200 words will be intercepted and an ellipsis will be added at the end of the sub-paragraph to form a summary. At this time, you can use the substr_replace() function to implement this function. Due to space reasons, only 40 will be demonstrated here. Character limit:
$article = "BREAKING NEWS: In ultimate irony, man bites dog.";
$summary = substr_replace($article, "...", 40);
$summary = "BREAKING NEWS :In ultimate irony, man bi..."
3. Count the number of characters and words in the string
I believe you often see some blogs or news articles to summarize the total word count of the article, or we often When you see some submission requirements, within a certain word count range, you can use the str_word_count() function to calculate the total word count of the article:
$article = "BREAKING NEWS: In ultimate irony, man bites dog.";
$wordCount = str_word_count($article); // $wordCount = 8
Sometimes you need to more strictly control the space used by contributors, such as some comments, etc., if you want to know how many characters are included An array, please use the count_chars() function.
4. Parse CSV files
Data is usually stored in the file in comma-delimited form (such as a known CSV file). CSV files use a comma or something similar to Predefined symbols form each column of strings into a separate row. You may often create PHP scripts to import this data, or parse out what you need. Over the years, I have also seen many methods of parsing CSV files. The most common is to use a combination of fgets() and explode() functions to read and parse files. However, the easiest way is to use a function to solve the problem, but it is not part of PHP's string processing library. :fgetcsv() function, using fopen() and fgetcsv() functions, we can easily parse this 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 a string array
Sometimes, you may need to create CSV files and read from these files at the same time. This means that you need to convert those comma-separated strings into data if the data was originally retrieved from the database. , then it is likely to only provide you with an array. At this time, you can use the implode() function to convert these strings into an array:
$csv = implode(",", $record);
6. Convert URLs into hyperlinks
Many WYSIWYG editors currently provide toolbars that allow users to mark text, including hyperlinks. However, you can easily automate this process when the content is rendered on the page. At the same time, to ensure that you do not encounter additional errors, to convert into a hyperlink URL, you can use the preg_replace() function, which can search for a string according to a regular expression and defines the structure of the URL:
$url = " LanFengye, LLC (http://www.phpfensi.com)";
$url = preg_replace("/http://([A-z0-9./-]+)/", "$0", $ url);
// $url = "LanFengye, LLC (http://www.phpfensi.com)"
7. Remove HTML tags from a string
As a web developer, one of the main jobs It is to ensure that the user input does not contain dangerous characters. If so, this will lead to SQL injection or script attacks. The PHP language contains many security features that can help you filter data, including extending the filter. For example, you You can allow users to have some basic HTML statements, including some comments, to achieve this function. You can use the check function: strip_tags(), which by default removes all HTML tags from the string. But it also allows you to override the default or tags you specify. For example, in the following example, you can remove all tags:
$text = strip_tags($input, "");
8. Compare two strings
Compare two strings to ensure that they are the same. For example, to determine whether the password entered by the user for the first time and the second time is the same, you can use the substr_compare() function to easily achieve this:
$pswd = "secret";
$pswd2 = "secret";
if (! strcmp($pswd, $pswd2))
{echo "The passwords are not identity!";
}
If you want to determine whether two strings are case-insensitive, you can use the strcasecmp() function.
9. Convert newlines
In this article I Introducing how to easily convert a hyperlinked URL, now introduce the nl2br() function, which can help you convert any line breaks into HTML tags.
$comment = nl2br($comment);
10. Apply automatically To apply automatic word wrapping, 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 proposal that all men are created equal.";
echo wordwrap($speech, 30); Executing the above code, 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 proposal that all men are created equal.
addcslashes — Add backslash escape characters to some characters in the string
addslashes — Use Escape the characters in the string in the specified way
bin2hex — Convert binary data into hexadecimal representation
chop — Alias function of rtrim()
chr — Return the ASCII code of a character
chunk_split — Split the string into small pieces according to a certain character length
convert_cyr_string — Convert Cyrillic characters to other characters
convert_uudecode — Decrypt a string
convert_uuencode — Encrypt a string
count_chars — Return a string Character usage information
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 write directly to the document stream
get_html_translation_table — Return HTML entities that can be converted
hebrev — Convert Hebrew-encoded strings into visual text
hebrevc — Encode Hebrew Convert a string into visual text
html_entity_decode — The inverse function of the htmlentities () function, convert HTML entities into characters
htmlentities — Convert some characters in the string into HTML entities
htmlspecialchars_decode — htmlspecialchars() function Inverse function, convert HTML entities into characters
htmlspecialchars — Convert some characters in a string into HTML entities
implode — Convert an array into a string using a specific delimiter
join — Convert an array into a string, implode Alias of () function
levenshtein — Calculate the difference between two words
localeconv — Get number-related format definitions
ltrim — Remove the blanks or specified characters on the left side of the string
md5_file — MD5 a file Algorithm encryption
md5 — Encrypt a string with MD5 algorithm
metaphone — Determine the pronunciation rules of a string
money_format — Format the output of numbers according to parameters
nl_langinfo — Query language and local information
nl2br — Replace the newline character "n" in the string with "
"
number_format — Format the output of the number according to the parameters
ord — Convert an ASCII code to a character
parse_str — Convert strings in a certain format into variables and values
print — used to output a single value
printf — display data as required
quoted_printable_decode — encrypt a string into an 8-bit binary string
quotemeta — Escape several specific characters
rtrim — Remove the blanks or specified characters on the right side of the string
setlocale — Set local formats for numbers, dates, etc.
sha1_file — Perform SHA1 algorithm on a file Encryption
sha1 — Encrypt a string with the SHA1 algorithm
similar_text — Compare two strings and return the number of similar characters that the system thinks Returns, but does not output
sscanf — can format strings
str_ireplace — matches and replaces strings like the str_replace() function, but is not case-sensitive
str_pad — pads both sides of the string
str_repeat — Repeat combinations of strings
str_replace — Match and replace strings
str_rot13 — Encrypt strings with ROT13
str_shuffle — Randomly sort the characters in a string
str_split — Split a string The string is divided into an array according to the character spacing
str_word_count — Get English word information in a string
strcasecmp — Compare strings, case-insensitively
strchr — Return part of a string through comparison Alias of the strstr() function
strcmp — Compare characters String size comparison
strcoll – Compare string size according to local settings
strcspn – Return the value of the continuous non-matching length of characters
strip_tags – Remove HTML and PHP code in a string
stripcslashes – Reverse escape The addcslashes() function escapes the processed string
stripos — Finds and returns the position of the first match, matching is not case sensitive
stripslashes — The addslashes() function escapes the processed string
stristr — Returns parts of a string by comparison, case-insensitive comparisons
strlen — Gets the encoded length of a string
strnatcasecmp — Compares strings using natural ordering, case-insensitive
strnatcmp — Compare the size of strings using natural sorting
strncasecmp — Compare the size of the first N characters of the string, case-insensitive
strncmp — Compare the size of the first N characters of the string
strpbrk — Returns a part of a string by comparison
strpos — Finds and returns the position of the first match
strrchr — Returns a part of a string by comparing from back to front
strrev — Reverses all letters in the string Arrange
strripos — Search from back to front and return the position of the first match, match is not case sensitive
strrpos — Search from back to front and return the position of the first match
strspn — Match and return consecutive characters The value of the occurrence length
strstr — Returns part of a string by comparison
strtok — Splits the string by a specified number of characters
strtolower — Converts the string to lowercase
strtoupper — Converts the string to uppercase
strtr — compare and replace strings
substr_compare — compare truncated strings
substr_count — count the number of occurrences of a certain character segment in a string
substr_replace — replace some characters in a string
substr — intercept the string
trim — remove the blanks or specified characters on both sides of the string
ucfirst — convert the first letter of the given string to uppercase
ucwords — convert each character of the given string The first letter of the English word becomes uppercase
vfprintf — Return the data as required and write it directly into the document stream
vprintf — Display the data as required
vsprintf — Return the data as required, but not Output
wordwrap — split the string according to a certain character length