phpregexpreg-replaceplaceholdersquare-bracket

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.


Solution

  • $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 \[.+\]