When we start working with PHP String functions, we have to learn some useful PHP String operation using PHP predefined functions. Today we talk about some most used PHP functions which use to manipulate PHP strings. Here are some we defined or explained with an example. There are 5 most used PHP string manipulation functions listed below:
Complete Explanation of PHP String functions
1. Substr in PHP (PHP substr())
Substr in PHP, also on the full form is called PHP substring. In PHP substring we cut out some part of the string from where we want. Using PHP substr(), in this function, we pass the required parameter than execute for getting the result. Below check the syntax of the PHP substr() function.
substr(string_name, start_position, string_length_to_cut)
PHP substr() Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php // PHP program to explain substr() function PHPSubstring($str){ $len = strlen($str); echo substr($str, 4), "<br/>"; echo substr($str, 5, $len), "<br/>"; echo substr($str, -2, 8), "<br/>"; echo substr($str,-4, -5), "<br/>"; } // Driver Code $str="PHPcoderTECH"; PHPSubstring($str); ?> //Output: oderTECH derTECH CH |
2. PHP String Length (PHP strlen())
Using PHP strlen() function we can get the length of the string.
strlen($string)
PHP strlen() Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php // PHP program to find the // length of a given string $str = "php coder tech"; // prints the length of the string // including the space echo strlen($str); ?> //O/U: 14 |
3. PHP String Replace (php str_replace, php regex replace)
In PHP, if we want replace any particular string, any integer or any type of data we use php str_replace() function. Example shown below.
PHP str_replace() Example:
1 2 3 4 5 6 7 |
<?php $my_str = 'If the facts do not fit the theory, change the facts.'; // Display replaced string echo str_replace("facts", "truth", $my_str); ?> |
4. PHP String Cast
1 2 3 4 5 |
<?php $string_var = "string value for php type"; $int_var = (int)$string_var; var_dump($int_var); ?> |
User Editor to check the O/P: Click Here
5. PHP Escape String (escape_string PHP)
1 2 3 4 5 6 7 |
Either escape the quote: $text1= "From time to \"time\""; or use single quotes to denote your string: $text1= 'From time to "time"'; |
Know more about PHP String functions, check the PHP official site,
https://www.php.net/manual/en/language.types.string.php
Happy Coding..!