Remove the First character from a String in PHP

This article, will discuss multiple ways to remove the first character from a string in PHP.

Table Of Contents

Introduction

Sometimes, while working with strings in PHP, you may encounter a situation where you need to remove the first character from a string. This could be for reasons like formatting adjustments, data cleanup, or processing user input. Let’s see how to do that.

Method 1: Using substr

The substr function in PHP is used to return a part of a string. It can be effectively used to remove the first character of a string by starting the substring from the second character. The syntax for substr is:

substr(string $string, int $start [, int $length ])

To remove the first character, we set the $start parameter to 1, which means starting from the second character of the string. If $length is not specified, the remainder of the string will be returned.

Let’s see the complete example,

<?php
$originalString = "This is a sample string";

// Remove the first character
$modifiedString = substr($originalString, 1);

// Outputs: his is a sample string
echo $modifiedString;
?>

Output

his is a sample string

In this snippet, $originalString is the string from which we want to remove the first character. We use substr to create $modifiedString, which is the original string minus its first character.

Method2 2: Using String Slicing with Array Syntax

PHP strings can be accessed like arrays, where each character in the string can be accessed via its index. Using this characteristic, we can slice the string to remove the first character.

Let’s see the complete example,

<?php
$originalString = "This is a sample string";

// Remove the first character using array slicing
$modifiedString = "";

// Iterate over all characters of string
// and join them into a newstring except first character
for ($i = 1; $i < strlen($originalString); $i++)
{
    $modifiedString .= $originalString[$i];
}

echo $modifiedString; // Outputs: his is a sample string
?>

Output

his is a sample string

Here, we loop through the $originalString starting from the second character (index 1) and concatenate each character to $modifiedString. This effectively removes the first character from the original string.

Summary

So, this way we can remove the first character from a String in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top