Remove brackets from a String in PHP

This article, will discuss multiple ways to remove brackets from a string in PHP.

Table Of Contents

Background

When working with strings in PHP, you might encounter situations where you need to remove brackets. This could be part of cleaning or formatting text data. For instance, given a string like “This is a [sample] string (example)”, the aim is to remove all instances of (, ), [, and ], resulting in “This is a sample string example”.

Solution 1: Using str_replace()

The str_replace() function in PHP can be used to replace all occurrences of specified characters with another character or an empty string. In this case, you can use it to replace both square and round brackets with an empty string.

Let’s see the complete example,

<?php
$originalString = "This is a [sample] string (example)";

// Remove square and round brackets
$cleanString = str_replace(array('[', ']', '(', ')'), '', $originalString);

// Display the result
echo $cleanString;
?>

Output

This is a sample string example

In this example, str_replace(array(‘[‘, ‘]’, ‘(‘, ‘)’), ”, $originalString) replaces all occurrences of [, ], (, and ) in $originalString with an empty string. It’s a straightforward and efficient method to remove specific characters from a string.

Solution 2: Using Regular Expressions with preg_replace()

For more complex scenarios or patterns, you can use preg_replace() with a suitable regular expression.

Let’s see the complete example,

<?php
$originalString = "This is a [sample] string (example)";

// Regular expression to remove square and round brackets
$cleanString = preg_replace('/[[]()]/', '', $originalString);

// Display the result
echo $cleanString;
?>

Output

This is a sample string example

In this code, preg_replace(‘/[[]()]/’, ”, $originalString) uses a regular expression that matches square brackets ([[]]) and round brackets (()), replacing them with an empty string. The square brackets need to be escaped within the regular expression pattern.

Summary

To remove brackets from a string in PHP, you can use the str_replace() function for a simple and direct approach or preg_replace() with a regular expression for more complex patterns. Both methods effectively clean up strings by removing unwanted bracket characters, a common requirement in text processing and data manipulation tasks.

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