PHP String Operators Tutorial with Examples

In PHP, string operators are used to manipulate and combine string values.

There are only two main string operators in PHP: the concatenation operator (.) and the concatenation assignment operator (.=).

However, strings can also be manipulated using various functions and techniques that extend the use of these operators.

This tutorial will cover:

Let’s dive into each of these topics with examples and explanations.

1. Concatenation Operator (.)

The concatenation operator (.) is used to combine two or more strings into a single string. This is a common operation when you need to join multiple strings together.

Syntax:

$string1 . $string2

Example:

<?php
$firstName = "John";
$lastName = "Doe";

// Concatenate first and last name
$fullName = $firstName . " " . $lastName;

echo $fullName;  // Outputs: John Doe
?>
  • In this example, the . operator is used to join $firstName and $lastName into a single string, with a space in between.

Example (Concatenating Multiple Strings):

<?php
$greeting = "Hello";
$name = "Alice";

// Concatenating multiple strings
$welcomeMessage = $greeting . ", " . $name . "!";

echo $welcomeMessage;  // Outputs: Hello, Alice!
?>
  • Here, we use the . operator multiple times to concatenate the greeting, name, and punctuation.

2. Concatenation Assignment Operator (.=)

The concatenation assignment operator (.=) appends the right-hand string to the left-hand variable and updates the variable with the new value. This is a shorthand way of concatenating a string to an existing variable.

Syntax:

$variable .= string;

Example:

<?php
$message = "Welcome";

// Append more strings using .=
$message .= " to PHP programming!";
$message .= " Enjoy learning.";

echo $message;  // Outputs: Welcome to PHP programming! Enjoy learning.
?>
  • In this example, the .= operator appends multiple strings to the $message variable, updating it with each operation.

3. Common String Manipulation Functions

In addition to the string operators, PHP provides several built-in functions for working with strings. These functions allow you to measure the length of a string, find substrings, replace parts of a string, and more.


3.1 strlen() – Getting the Length of a String

The strlen() function returns the number of characters in a string (including spaces and punctuation).

Example:

<?php
$message = "Hello, World!";
$length = strlen($message);

echo "The length of the message is: " . $length;  // Outputs: 13
?>
  • The strlen() function counts the number of characters in the string “Hello, World!”, which is 13 characters (including the comma and space).

3.2 strpos() – Finding the Position of a Substring

The strpos() function returns the position of the first occurrence of a substring within a string. If the substring is not found, it returns false.

Example:

<?php
$message = "Learning PHP is fun!";
$position = strpos($message, "PHP");

if ($position !== false) {
    echo "'PHP' found at position: " . $position;  // Outputs: 'PHP' found at position: 9
} else {
    echo "'PHP' not found in the string.";
}
?>
  • In this example, the strpos() function finds that the substring “PHP” starts at position 9 in the string.

3.3 str_replace() – Replacing a Substring

The str_replace() function replaces all occurrences of a substring with another string.

Syntax:

str_replace(search, replace, subject);

Example:

<?php
$message = "I love Python programming!";
$updatedMessage = str_replace("Python", "PHP", $message);

echo $updatedMessage;  // Outputs: I love PHP programming!
?>
  • In this case, str_replace() replaces “Python” with “PHP” in the original string.

3.4 substr() – Extracting a Substring

The substr() function extracts a portion of a string, starting at a specified position and optionally for a specified length.

Syntax:

substr(string, start, length);

Example:

<?php
$message = "Welcome to PHP programming!";
$subString = substr($message, 11, 3);

echo $subString;  // Outputs: PHP
?>
  • The substr() function extracts a substring starting at position 11 and of length 3, resulting in “PHP”.

Example (Extracting to the End of the String):

<?php
$sentence = "Learning PHP is fun!";
$subString = substr($sentence, 9);

echo $subString;  // Outputs: PHP is fun!
?>
  • If the length is omitted, substr() extracts the substring from the starting position to the end of the string.

3.5 strtolower() and strtoupper() – Changing Case

  • strtolower() converts all characters of a string to lowercase.
  • strtoupper() converts all characters of a string to uppercase.

Example (Converting to Lowercase):

<?php
$message = "HELLO, WORLD!";
$lowerCaseMessage = strtolower($message);

echo $lowerCaseMessage;  // Outputs: hello, world!
?>

Example (Converting to Uppercase):

<?php
$message = "hello, world!";
$upperCaseMessage = strtoupper($message);

echo $upperCaseMessage;  // Outputs: HELLO, WORLD!
?>
  • These functions are useful for normalizing text, for example, when checking user input.

Summary of String Operators and Functions:

Operator/Function Description Example
. Concatenates two strings $str1 . $str2
.= Appends a string to a variable $str1 .= “World!”
strlen() Returns the length of a string strlen(“Hello”)
strpos() Finds the position of a substring strpos(“Hello, PHP”, “PHP”)
str_replace() Replaces occurrences of a substring str_replace(“a”, “b”, “apple”)
substr() Extracts a portion of a string substr(“Hello”, 1, 3)
strtolower() Converts a string to lowercase strtolower(“HELLO”)
strtoupper() Converts a string to uppercase strtoupper(“hello”)

Conclusion

String operators and functions in PHP allow you to efficiently work with and manipulate strings. Here’s what we covered in this tutorial:

  • Concatenation (.) and concatenation assignment (.=) operators for joining strings.
  • Common string manipulation functions such as:
    • strlen() for getting the length of a string.
    • strpos() for finding the position of a substring.
    • str_replace() for replacing parts of a string.
    • substr() for extracting substrings.
    • strtolower() and strtoupper() for changing the case of a string.

Mastering these operators and functions will help you handle text processing tasks effectively in PHP.

 

Related posts

PHP Static Methods: A Tutorial with Examples

PHP Deleting Files: A Tutorial with Examples

PHP Copying Files: A Tutorial with Examples