PHP String
- Hello guys ! In this tutorial we will learn about PHP String !
- In PHP, strings can be defined using single quotes (''), double quotes ("") or the heredoc syntax (<<<). Here's an example of defining a string using "double" quotes:
PHP Example
Edit it yourself
<!DOCTYPE html>
<html>
<body>
<?php
$string = "Hello world";
?>
</body>
</html>
Output
Edit it yourselfHello World
PHP String Function
- PHP provides numerous functions to manipulate and work with strings. Let's explore some commonly used string operations:
PHP Concatenation:
- You can concatenate (join) two or more strings using the concatenation operator (.) or the concatenation assignment operator(.=).
PHP Example
Edit it yourself
<!DOCTYPE html>
<html>
<body>
<?php
$string1 = "Hello";
$string2 = "World";
$concat = $string1.$string2;
echo $concat;
?>
</body>
</html>
Output
Edit it yourselfHello World
PHP Srting length :
- The strlen() function is used to determine the length of a string, which is the number of characters it contains.
PHP Example
Edit it yourself
<!DOCTYPE html>
<html>
<body>
<?php
$string = "Hello, world!";
$length = strlen($string);
echo $length;
?>
</body>
</html>
Output
Edit it yourself13
PHP Substring Extraction:
- You can extract a portion of a string using the substr() function. It takes the string and the starting index as arguments, and optionally, the length of the substring.
PHP Example
Edit it yourself
<!DOCTYPE html>
<html>
<body>
<?php
$string = "Hello, world!";
$sub = substr($string, 0, 5);
echo $sub;
?>
</body>
</html>
Output
Edit it yourselfHello
PHP Searching and Replacing:
- PHP provides functions like strpos() and str_replace() to search for specific substrings within a string and replace them with new values.
PHP Example
Edit it yourself
<!DOCTYPE html>
<html>
<body>
<?php
$string = "Hello, world!";
$position = strpos($string, "world");
$newString = str_replace("world", "PHP", $string);
?>
</body>
</html>
Output
Edit it yourselfHello, PHP !
PHP Case Manipulation :
- PHP has functions to convert strings between different cases, such as strtolower() (to lowercase), strtoupper() (to uppercase), and ucfirst() (to capitalize the first character).
PHP Example
Edit it yourself
<!DOCTYPE html>
<html>
<body>
<?php
$string = "hello, world!";
$lowercase = strtolower($string);
$uppercase = strtoupper($string);
$capitalized = ucfirst($string);
echo $lowercase;
echo $uppercase;
echo $capitalized;
?>
</body>
</html>
Output
Edit it yourselfhello, world! HELLO, WORLD! Hello, world!