Modifying PHP Strings
PHP provides several functions for modifying strings, including:
- strtolower(): Converts a string to lowercase.
- strtoupper(): Converts a string to uppercase.
- trim(): Removes whitespace from the beginning and end of a string.
- substr(): Extracts a portion of a string.
- str_replace(): Replaces a portion of a string with another string.
- str_split(): Splits a string into an array.
- implode(): Joins an array of strings into a single string.
Example of Modifying PHP Strings
<?php
$string = 'Hello, World!';
echo strtolower($string) . "\n";
// Outputs: hello, world!
echo strtoupper($string) . "\n";
// Outputs: HELLO, WORLD!
echo trim($string) . "\n";
// Outputs: Hello, World!
echo substr($string, 0, 5) . "\n";
// Outputs: Hello
echo str_replace('World', 'Earth', $string) . "\n";
// Outputs: Hello, Earth!
$stringArray = str_split($string);
echo implode('-', $stringArray) . "\n";
// Outputs: H-e-l-l-o-,- -W-o-r-l-d-!
?>
Output:
hello, world!
HELLO, WORLD!
Hello, World!
Hello
Hello, Earth!
H-e-l-l-o-,- -W-o-r-l-d-!
Explanation: This example demonstrates the use of several functions for modifying strings in PHP, including strtolower()
, strtoupper()
, trim()
, substr()
, str_replace()
, str_split()
, and implode()
.
Single Line Example
<?php
echo strtolower('HELLO WORLD!') . "\n";
echo strtoupper('hello world!') . "\n";
echo trim(' Hello World! ') . "\n";
echo substr('Hello World!', 0, 5) . "\n";
echo str_replace('World', 'Earth', 'Hello World!') . "\n";
$stringArray = str_split('Hello World!');
echo implode('-', $stringArray); ?>
Output:
hello world!
HELLO WORLD!
Hello World!
Hello
Hello Earth!
H-e-l-l-o- -W-o-r-l-d-!