PHP - Modify Strings

In PHP, you can modify strings in many ways using built-in functions. Here's a quick overview of common operations:

1. Concatenation

$name = "John"; $greeting = "Hello, " . $name; // "Hello, John"

2. Changing Case

strtoupper("hello"); // "HELLO" strtolower("HELLO"); // "hello" ucfirst("hello"); // "Hello" lcfirst("Hello"); // "hello" ucwords("hello world"); // "Hello World"

3. Trimming

trim(" hello "); // "hello" ltrim(" hello"); // "hello" rtrim("hello "); // "hello"

4. Replacing Substrings

 str_replace("world", "PHP", "Hello world"); // "Hello PHP" str_ireplace("WORLD", "PHP", "Hello world"); // Case-insensitive

5. Extracting Substrings

substr("Hello world", 6); // "world" substr("Hello world", 0, 5); // "Hello"

6. String Length

strlen("Hello"); // 5

7. Splitting and Joining Strings

explode(" ", "PHP is fun"); // ["PHP", "is", "fun"] implode("-", ["PHP", "is", "fun"]); // "PHP-is-fun"

8. Searching Strings

strpos("Hello world", "world"); // 6 str_contains("Hello world", "world"); // true (PHP 8+)