PHP String Manipulation (Step-by-Step Guide with Examples)

PHP string manipulation allows developers to modify, format, and process text dynamically. Whether you’re working with user inputs, database queries, or content generation, mastering PHP string functions is crucial for writing efficient code.

Declaring and Printing Strings in PHP

<?php
// Using double quotes
$string1 = "Hello, PHP!";

// Using single quotes
$string2 = 'Welcome to PHP!';

// Printing a string
echo $string1;
?>

Tip:

  • Double quotes allow variable interpolation ($var inside string gets replaced).
  • Single quotes do not process variables.

String Concatenation

Using . Operator

<?php
$firstName = "John";
$lastName = "Doe";
$fullName = $firstName . " " . $lastName;
echo $fullName; // Output: John Doe
?>

Tip: Use .= for appending strings.

 
<?php
$text = "Hello";
$text .= " World!";
echo $text; // Output: Hello World!
?>

Changing Case in Strings

Convert to Uppercase (strtoupper)

<?php
$text = "php is awesome!";
echo strtoupper($text); // Output: PHP IS AWESOME!
?>

Convert to Lowercase (strtolower)

<?php
$text = "HELLO PHP!";
echo strtolower($text); // Output: hello php!
?>

Capitalize First Letter (ucfirst)

<?php
$text = "php is great!";
echo ucfirst($text); // Output: Php is great!
?>

Capitalize Each Word (ucwords)

<?php
$text = "php is fun!";
echo ucwords($text); // Output: Php Is Fun!
?>

Extracting Parts of a String

Using substr() to Get a Substring

<?php
$text = "Hello, PHP!";
echo substr($text, 7, 3); // Output: PHP
?>

Tip:

  • substr($text, 0, 5) → Extracts first 5 characters
  • substr($text, -3) → Extracts last 3 characters

Finding and Replacing Text

Finding a Substring (strpos)

<?php
$text = "Welcome to PHP!";
echo strpos($text, "PHP"); // Output: 11
?>

Replacing Text (str_replace)

<?php
$text = "Hello, World!";
$newText = str_replace("World", "PHP", $text);
echo $newText; // Output: Hello, PHP!
?>

Tip: Use str_ireplace() for case-insensitive replacement.

Best Practices for PHP String Manipulation

  • Use trim() to clean up user input
  • Use str_replace() for simple replacements, preg_replace() for advanced cases
  • Use strpos() to check if a string contains a keyword
  • Always escape strings (htmlspecialchars()) when handling user input

Read More

How to Create Database in MySQL

  • By admin
  • November 27, 2021
  • 22 views
How to Create Database in MySQL

How to create table in MySQL

  • By admin
  • November 6, 2021
  • 17 views
How to create table in MySQL

MySQL commands with examples

  • By admin
  • September 11, 2021
  • 37 views
MySQL commands with examples

MySQL use database

  • By admin
  • May 28, 2021
  • 18 views
MySQL use database

System Software

  • By admin
  • May 20, 2021
  • 24 views

Introduction to software

  • By admin
  • May 13, 2021
  • 18 views
Introduction to software