Seven interesting PHP functions
- 2020-03-30 02:54:25
- OfStack
PHP has many built-in functions, most of which are widely used by programmers. But there are also some functions hidden in the corner, and this article introduces you to seven lesser-known but very useful functions. Programmers who haven't used it might as well come and have a look.
1. The highlight_string ()
The highlight_string() function is useful when you need to show PHP code in a website. This function outputs or returns the syntax-highlighted version of a given PHP code by highlighting the colors defined in the program using PHP syntax.
Example:
<?php
highlight_string('<?php phpinfo(); ?>');
?>
2. The str_word_count ()
The function must pass an argument that returns the number of words based on the argument type. As follows:
<?php
$str = "How many words do I have?";
echo str_word_count($str); //Outputs 6
?>
3. The levenshtein ()
This function mainly returns the Levenshtein distance between two strings. Levenshtein distance, also known as edit distance, refers to the minimum number of edits required to convert from one string to the other between two strings. The permitted editing operations include replacing one character with another, inserting a character, and deleting a character. This function is useful for finding typos submitted by the user.
Example:
<?php
$str1 = "carrot";
$str2 = "carrrott";
echo levenshtein($str1, $str2); //Outputs 2
?>
4. Get_defined_vars ()
This function returns a multidimensional array containing a list of all defined variables, including environment variables, server variables, and user-defined variables.
Example:
print_r(get_defined_vars());
5. Escapeshellcmd ()
This function is used to avoid special symbols in the string to prevent users from playing tricks on the server system. This function can be used with two functions, exec() or system(), so as to reduce the malicious behavior of online users.
Example:
<?php
$command = './configure '.$_POST['configure_options'];
$escaped_command = escapeshellcmd($command);
system($escaped_command);
?>
6. Checkdate ()
This function can be used to check whether the date is valid, for example, year 0 to 32767, month 1 to December, and day varies with month and leap year.
Example:
<?php
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));
//Output
//bool(true)
//bool(false)
?>
7. Php_strip_whitespace ()
This function returns the source code file with the deleted PHP comments and white space characters, which is useful for comparing the actual amount of code with the amount of comments.
Example:
<?php
// PHP comment here
echo php_strip_whitespace(__FILE__);
// Newlines are considered whitespace, and are removed too:
do_nothing();
//Try the output
echo php_strip_whitespace(__FILE__); do_nothing();
?>