HiSpec
HiSpec

Reputation: 125

Remove text between [ ]

I have

string = 'blah blah [unwanted text] blah'

How do I use PHP to return 'blah blah blah'? I.e. I want to remove the text between square brackets. Would I use preg_replace?

Upvotes: 1

Views: 1373

Answers (4)

verdesmarald
verdesmarald

Reputation: 11866

Yes, you can use preg_replace('/\[[^]]*\]\s*/', '', $your_string)

Upvotes: 2

Sudan Hari
Sudan Hari

Reputation: 51

<?php
$string = 'blah blah [unwanted text] blah';
$x=explode("[",$string);
$y=explode("]",$string);
echo $x[0].$y[1];
?>

-- use this so that you can get the output as you expected.

Upvotes: 0

TheHe
TheHe

Reputation: 2972

complete solution:

$input = preg_replace('/\[[^\]]*\]\W*/i', '', $input);

Upvotes: 1

DhruvPathak
DhruvPathak

Reputation: 43235

You can use this regex: \[.*?\]

echo preg_replace('/\[.*?\]/', '', "blah blah [unwanted text] blah");

http://codepad.org/cNvpQOSg

Upvotes: 2

Related Questions