Functions that work with strings in PHP
PHP supports built-in functions for working with strings. In essence, if the functions are not provided or the situations are complicated, we can use algorithms to handle it, but with the help of built-in functions, it helps us to reduce algorithm writing time, do not need to care about how the math function behaves and only need to care about the input and output of the function.
Full reference here: https://www.php.net/manual/en/ref.strings.php
Some basic string functions:
strlen() : Returns the length of the string. strlen() is a built-in function that calculates the length of a string, including all special characters and spaces.
<?php echo strlen("Hello Toan!"); // output: 11 ?>
str_word_count() : The str_word_count() function returns the number of words in a string.
str_word_count(string, return_value, chars)
string: is the input string.
return_value: specifies the retum value of the function and can be one of the following: 0 (returns the number of words found), 1 (returns an array containing all the words found in the string) or 2 ( returns an associative array) (optional)
chars: specifies a list of additional characters to be treated as a word (optional)
<?php echo str_word_count("Hello Toan"); //output: 2 ?>
strrev() : This is a predefined function used to reverse a string. This is one of the most basic string operations that programmers and developers use.
string strrev(string $string );
<?php echo strrev("Hello"); // output: olleH ?>
strpos() : This function is used to find a specified text in a string. If there is a match, it returns the character position of the first matching value that is an integer; if none, it returns FALSE .
strpos($string, $find, $start) ;
<?php echo strpos("Hello Toan!", "Toan"); // output: 6 ?>
str_replace() : Function used to replace characters in a string.
str_replace($search, $replace, $string, $count)
- $search indicates the value being searched
- $replace is the replacement value
- $string is the string to replace
- $count indicates the number of successful replacements
<?php echo str replace("Toan", "Hello", "Hello Toan!"); //output: Hello Hello! ?>
ucwords() : This function returns a string after converting the first character of each word in the given string to uppercase.
string ucwords(string $str)
<?php $str="my name is toan."; $str_ucwords($str); // output: My Name Is Toan ?>