Reputation: 337
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
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
Reputation: 3647
$str_1 = preg_replace("/\[[A-Z0-9a-z\w ]+\]/", "", $str_1);
$str_2 = preg_replace("/\[[A-Z0-9a-z\w ]+\]/", "", $str_2);
If you want to discard anything that is in between third bracket your regex is actually simpler.
That will be \[.+\]
Upvotes: -1