Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

String Manipulation in PHP

Introduction

String manipulation is a fundamental aspect of programming that involves altering, parsing, and analyzing strings. PHP provides a rich set of functions to handle strings efficiently. This tutorial will cover various string manipulation techniques in PHP with examples.

1. Concatenation

Concatenation is the process of joining two or more strings together. In PHP, the concatenation operator is the dot (.) symbol.

<?php
$string1 = "Hello";
$string2 = "World";
$result = $string1 . " " . $string2;
echo $result; // Outputs: Hello World
?>

2. String Length

The strlen() function is used to get the length of a string.

<?php
$string = "Hello World";
$length = strlen($string);
echo $length; // Outputs: 11
?>

3. String Position

The strpos() function is used to find the position of the first occurrence of a substring in a string.

<?php
$string = "Hello World";
$position = strpos($string, "World");
echo $position; // Outputs: 6
?>

4. Substring

The substr() function is used to extract a part of a string.

<?php
$string = "Hello World";
$substring = substr($string, 0, 5);
echo $substring; // Outputs: Hello
?>

5. String Replace

The str_replace() function is used to replace all occurrences of a search string with a replacement string.

<?php
$string = "Hello World";
$newString = str_replace("World", "PHP", $string);
echo $newString; // Outputs: Hello PHP
?>

6. String to Uppercase

The strtoupper() function is used to convert a string to uppercase.

<?php
$string = "Hello World";
$uppercaseString = strtoupper($string);
echo $uppercaseString; // Outputs: HELLO WORLD
?>

7. String to Lowercase

The strtolower() function is used to convert a string to lowercase.

<?php
$string = "Hello World";
$lowercaseString = strtolower($string);
echo $lowercaseString; // Outputs: hello world
?>

8. Trim Strings

The trim() function is used to remove whitespace or other predefined characters from both sides of a string.

<?php
$string = " Hello World ";
$trimmedString = trim($string);
echo $trimmedString; // Outputs: Hello World
?>

Conclusion

This tutorial has covered the basics of string manipulation in PHP, including concatenation, string length, string position, substrings, string replace, and changing string cases. These fundamental operations are essential for effective PHP development.