PHP / PHP Arrays and Strings

String Manipulation Techniques

Handling text strings is a common task in PHP. This tutorial will guide you through various techniques for manipulating and formatting strings in PHP.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Explores array manipulation and string handling in PHP.

1. Introduction

In this tutorial, we will explore various techniques for manipulating and formatting strings in PHP. PHP offers a wide array of functions to work with strings, which are sequences of characters. We will cover key functions like strlen(), str_replace(), substr(), and strpos().

By the end of this tutorial, you will understand how to:

  • Find the length of a string.
  • Replace parts of a string.
  • Extract parts of a string.
  • Find the position of a substring in a string.

Prerequisites: Basic knowledge of PHP syntax and programming concepts.

2. Step-by-Step Guide

String Length with strlen()

The strlen() function returns the length of a string.

Example:

$text = "Hello, World!";
$length = strlen($text);
echo $length; // Output: 13

String Replacement with str_replace()

The str_replace() function replaces some characters in a string with some other characters.

Example:

$text = "Hello, World!";
$new_text = str_replace("World", "Dolly", $text);
echo $new_text; // Output: "Hello, Dolly!"

Substring Extraction with substr()

The substr() function returns a part of a string.

Example:

$text = "Hello, World!";
$part = substr($text, 7, 5);
echo $part; // Output: "World"

Find Substring Position with strpos()

The strpos() function finds the position of the first occurrence of a substring in a string.

Example:

$text = "Hello, World!";
$pos = strpos($text, "World");
echo $pos; // Output: 7

3. Code Examples

Now, let's see some practical examples:

Example 1: Counting words in a string

$text = "The quick brown fox jumps over the lazy dog.";
$word_count = str_word_count($text);
echo $word_count; // Output: 9

Example 2: Reversing a string

$text = "Hello, World!";
$reversed = strrev($text);
echo $reversed; // Output: "!dlroW ,olleH"

Example 3: Converting a string to uppercase

$text = "Hello, World!";
$upper = strtoupper($text);
echo $upper; // Output: "HELLO, WORLD!"

4. Summary

We have covered how to:

  • Find the length of a string with strlen().
  • Replace parts of a string with str_replace().
  • Extract parts of a string with substr().
  • Find the position of a substring in a string with strpos().

Next, you can explore more advanced string functions like strstr(), strrchr(), str_split(), etc.

5. Practice Exercises

  1. Write a PHP script to remove all whitespaces from a string.
$text = "Hello, World! How are you?";
$no_spaces = str_replace(" ", "", $text);
echo $no_spaces; // Output: "Hello,World!Howareyou?"
  1. Write a PHP script to find the last occurrence of a character in a string.
$text = "Hello, World! How are you?";
$pos = strrpos($text, "o");
echo $pos; // Output: 22
  1. Write a PHP script to split a string into an array of words.
$text = "The quick brown fox jumps over the lazy dog.";
$words = str_word_count($text, 1);
print_r($words);
// Output: Array ( [0] => The [1] => quick [2] => brown [3] => fox [4] => jumps [5] => over [6] => the [7] => lazy [8] => dog )

Remember to practice regularly to become proficient at string manipulation in PHP!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

Random Password Generator

Create secure, complex passwords with custom length and character options.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help