Jonathan Besomi
Jonathan Besomi

Reputation: 337

Remove all square brace placeholders from a string

I would like to delete, in this two strings, the part in square brackets. In this example I would like to print the two string without "[No Change]" and "[New]".

<?php

$str_1 = "[No Change]  Busta Rhymes ft. Kanye West, Lil Wayne & Q-Tip - Thank You";
$str_2 = "[New] B.o.B ft. Chris Brown - Throwback";

$str_1 = preg_replace("/\[[^A-Z0-9a-z\w ]\]/", "", $str_1);
$str_2 = preg_replace("/\[[^A-Z0-9a-z\w ]\]/", "", $str_2);

echo $str_1; // Result: [No Change]  Busta Rhymes ft. Kanye West, Lil Wayne & Q-Tip - Thank You
echo $str_2; // Result: [New] B.o.B ft. Chris Brown - Throwback
?>

I write this PHP code but seems not to work.

Upvotes: 2

Views: 103

Answers (3)

newman
newman

Reputation: 2719

There is working regexp code

$str_1 = preg_replace('/\[[^\]]*\]/', "", $str_1);
$str_2 = preg_replace('/\[[^\]]*\]/', "", $str_2);

And don't use double quote for regexp then you need escape char '\' too

Upvotes: 2

chanchal118
chanchal118

Reputation: 3647

$str_1 = preg_replace("/\[[A-Z0-9a-z\w ]+\]/", "", $str_1);
$str_2 = preg_replace("/\[[A-Z0-9a-z\w ]+\]/", "", $str_2);

DEMO

If you want to discard anything that is in between third bracket your regex is actually simpler.
That will be \[.+\]

Upvotes: -1

10 cls
10 cls

Reputation: 1425

Try the following regex pattern:

/\[[^\]]*\]?/g

Upvotes: 1

Related Questions