Current Location: Home> Latest Articles> PHP Tutorial: How to Remove the First Character from the Right of a String

PHP Tutorial: How to Remove the First Character from the Right of a String

M66 2025-07-28

PHP Tutorial: How to Remove the First Character from the Right of a String

In PHP development, string manipulation is a common task, and one common requirement is to remove the first character from the right of a string. This article will introduce how to achieve this functionality using PHP functions and provide specific code examples.

Using the substr Function to Remove the First Character from the Right of a String

In PHP, the substr function can be used to extract a part of a string. We can use this function to easily remove the first character from the right of a string.

Here is a simple example that demonstrates how to use the substr function to remove the first character from the right of a string:

<?php
// Original string
$str = "Hello World";

// Use substr to remove the first character from the right
$newStr = substr($str, 0, -1);

// Output the string after removing the first character from the right
echo $newStr;
?>

In the above code, we define the original string "Hello World" and use the substr function to extract the substring. By setting the parameters to 0 and -1, substr starts extracting from the beginning of the string and removes the last character. The processed string is then output using the echo statement.

Using Regular Expressions to Remove the First Character from the Right of a String

In addition to the substr function, we can also use regular expressions to remove the first character from the right of a string. Here is an example using the preg_replace function:

<?php
// Original string
$str = "Hello World";

// Use regular expression to remove the first character from the right
$newStr = preg_replace('/.$/', '', $str);

// Output the string after removing the first character from the right
echo $newStr;
?>

In this example, the preg_replace function is used to match and remove the first character from the right of the string. The regular expression "/.$/" matches any character at the end of the string and replaces it with an empty string, effectively removing it.

Conclusion

By using the substr function or regular expressions, we can easily remove the first character from the right of a string. In actual development, developers can choose the appropriate method based on the specific requirements to improve the efficiency and readability of the code.