Remove characters from String after a character in PHP

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

Table Of Contents

Background

In PHP, you may often need to manipulate strings by removing all characters following a specific character. This is common in parsing URLs, file paths, or data cleanup tasks. For example, consider a string like this:

$originalString = "thispointer.com/page?param=123";

If you want to remove everything after the ? character, the desired output would be:

"thispointer.com/page"

Let’s explore some methods to achieve this.

Solution 1: Using explode()

The explode() function splits a string by a specified delimiter into an array. You can then use the first element of this array, which contains the string part before the delimiter.

Let’s see the complete example,

<?php
$originalString = "thispointer.com/page?param=123";
$delimiter = '?';

// Split the string into parts
$parts = explode($delimiter, $originalString);

// Get the first part of the string
$modifiedString = $parts[0];

echo $modifiedString;
?>

Output

thispointer.com/page

In this code:
– We split $originalString at the $delimiter (?) using explode().
– $parts[0] contains the string segment before the ?.
– This method is simple and works well when you are sure the delimiter exists in the string.

Solution 2: Using strstr()

Alternatively, strstr() can be used to find the first occurrence of a substring in a string and return all the text before it.

Let’s see the complete example,

<?php
$originalString = "thispointer.com/page?param=123";
$delimiter = '?';

// Get the part of the string before the delimiter
$modifiedString = strstr($originalString, $delimiter, true);

echo $modifiedString;
?>

Output

thispointer.com/page

In this code:
– strstr($originalString, $delimiter, true) searches for the $delimiter in $originalString.
– The third parameter true tells strstr() to return the part of the string before the first occurrence of the $delimiter.
– This function is particularly useful when you need to handle the possibility of the delimiter not being present in the string.

Summary

To remove characters after a specific character in a PHP string, both explode() and strstr() functions are effective. explode() is a good choice when the delimiter is guaranteed to be present, while strstr() offers a more robust solution that can handle cases where the delimiter might not exist in the string.

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