Home  >  Article  >  Backend Development  >  Detailed explanation of php string processing functions_PHP tutorial

Detailed explanation of php string processing functions_PHP tutorial

WBOY
WBOYOriginal
2016-07-20 10:59:07842browse

PHP's ability to process strings is very powerful, and there are many methods, 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 methods. ​

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. What we must mention here is the strlen() function:

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


2. Intercept text and create a summary

News websites usually intercept a paragraph of about 200 words and add an ellipsis at the end of the paragraph to form a summary. At this time, you can use the substr_replace() function to achieve this function. Due to space reasons, only the 40-character limit 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. Count the number of characters and words in the string


I believe you often see some blogs or news articles summarizing the total word count of the article, or we often see some submission requirements: within a certain word count range. At this time, 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 more strictly control the space used by contributors, such as some comments and so on. If you want to know how many characters make up an array, use the count_chars() function.

4. Parse CSV files

Data is usually stored in a file in comma-delimited form (such as a known CSV file). CSV files use a comma or similar predefined symbols to 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 seen many methods of parsing CSV files. The most common is to use a combination of fgets() and explode() functions. To read and parse the file, however, the easiest way to solve the problem is to use a function that is not part of PHP's string processing library: the fgetcsv() function. Using the 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


At some point, you may need to create CSV files and read from them at the same time, which means you need to convert those comma-separated strings into data. If the data was originally retrieved from a database, it would most likely only give you 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


Currently, many WYSIWYG editors provide toolbars that allow users to mark text, including hyperlinks. However, you can easily automate this process while ensuring that you don't encounter additional errors when the content is rendered to the page. To convert a hyperlink URL, you can use the preg_replace() function, which searches a string according to a regular expression and defines the structure of the URL:

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

from a string


As a web developer, one of your main jobs is to ensure that user input does not contain dangerous characters, which, if present, could lead to SQL injection or scripting attacks. The PHP language contains many security features that can help you filter data, including extending filters. For example, 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(). It removes all HTML tags from the string by default, but also allows overriding 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


Compares two strings to make sure 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 realize this:

$pswd = "secret";
$pswd2 = "secret";
if (! strcmp($pswd, $pswd2))
{ echo "The passwords are not identical!";
}If you want to determine whether two strings are case-insensitive, you can use the strcasecmp() function.

9. Convert line breaks


In this article I introduced how to easily convert a URL into a hyperlink, and now I introduce the nl2br() function, which can help you convert any newline character into an HTML tag.

$comment = nl2br($comment);


10. Apply automatic word wrapping


To apply 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 proposition that all men are created equal.";

echo wordwrap($speech, 30); Execute 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 proposition that all men are created equal.

addcslashes — Add backslash escape characters to some characters in a string
addslashes — Escape characters in a string in a specified way
bin2hex — Convert binary data to hexadecimal representation
chop — alias function for rtrim()
chr — Returns the ASCII code of a character
chunk_split — Split a string into small chunks 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 — Returns character usage information in a string
crc32 — Compute 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 delimiters
fprintf — Return data as required and write directly to the document stream
get_html_translation_table — Returns HTML entities that can be translated
hebrev — Convert a Hebrew-encoded string to visual text
hebrevc — Convert a Hebrew-encoded string to visual text
html_entity_decode — Inverse function of htmlentities () function, converts HTML entities to characters
htmlentities — Convert some characters in a string to HTML entities
htmlspecialchars_decode —The inverse function of htmlspecialchars() function, converts HTML entities into characters
htmlspecialchars — Convert some characters in a string to HTML entities
implode — Convert an array into a string using a specific delimiter
join — Convert array to string, alias of implode() function
levenshtein — Calculate the difference between two words
localeconv — Get number-related format definitions
ltrim — removes whitespace on the left side of a string or specified characters
md5_file — Encrypt a file with MD5 algorithm
md5 — Encrypt a string using the MD5 algorithm
metaphone — Determine the pronunciation rules of a string
money_format — Output of numbers formatted according to arguments
nl_langinfo — Query language and locale information
nl2br — Replace newline character "n" in a string with "

number_format — Output of numbers formatted according to parameters
ord — Convert an ASCII code to a character
parse_str — Convert strings in a certain format into variables and values ​​
print — used to print 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 — removes whitespace or specified characters
from the right side of a string setlocale — Set local formats for numbers, dates, etc.
sha1_file — Encrypt a file with SHA1 algorithm
sha1 — Encrypt a string with SHA1 algorithm
similar_text — Compares two strings and returns the number of similar characters considered by the system
soundex — Determine the pronunciation rules of a string
sprintf — returns data as required, but does not output
sscanf — can format strings
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 — Repeat combination of strings
str_replace — Match and replace strings
str_rot13 — Encrypt a string with ROT13
str_shuffle — Randomly sort the characters in a string
str_split — Split a string into an array according to character spacing
str_word_count — Get the English word information in the string
strcasecmp — Compare strings, case-insensitively
strchr — Alias ​​for the strstr() function that returns a portion of a string by comparison
strcmp — Compare string sizes
strcoll – Compare string sizes based on local settings
strcspn — Returns the value of the consecutive non-matching length of characters
strip_tags — Remove HTML and PHP code from a string
stripcslashes — Unescaping strings processed by the addcslashes() function
stripos — Find and return the position of the first match, matching is case-insensitive
stripslashes — Anti-escaping the strings processed by the addslashes() function
stristr — Returns parts of a string by comparison, case-insensitive
strlen — Get the encoded length of a string
strnatcasecmp — Compare strings using natural ordering, case-insensitive
strnatcmp — Size comparison of strings using natural ordering
strncasecmp — Compare the first N characters of a string, case-insensitive
strncmp — Compare the size of the first N characters of a string
strpbrk — Returns parts of a string
by comparison strpos — Find and return the position of the first match
strrchr — Returns a portion of a string
by comparing it backwards and forwards strrev — Reverse all letters in a string
strripos — Search backwards and return the position of the first match, matching is not case sensitive
strrpos – searches backward and returns the position of the first match
strspn — Match and return the value of the length of consecutive occurrences of characters
strstr — Returns parts of a string
by comparison strtok — Split a string using specified characters
strtolower — Convert a string to lowercase
strtoupper – Convert a string to uppercase
strtr — compare and replace strings
substr_compare — Compare strings after truncation
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 a string
trim — Remove whitespace or specified characters
on both sides of a string ucfirst — Converts the first letter of the given string to uppercase
ucwords — Capitalize the first letter of each English word in the given string
vfprintf — Return data as required and write directly to the document stream
vprintf — display data as required
vsprintf — Returns data as required, but does not output
wordwrap — Split a string according to a certain character length


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/445622.htmlTechArticlePHP’s ability to process strings is very powerful, and there are many methods, but sometimes you need to choose one The simplest and ideal solution. The article lists 10 common strings in PHP...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn