Brian
Brian

Reputation: 5028

Erasing multiple symbols from a string

I know that preg_replace('/[{}]/', '', $string); will erase curly brackets, but what if I had square brackets too and also needed to erase them?

Upvotes: 2

Views: 102

Answers (5)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76413

Why go through the trouble of using regex for this. If all you're doing is replacing 4 chars from a string:

str_replace(array('[',']','{','}'),'',$string);

Will do the same thing.

Upvotes: 3

Robert
Robert

Reputation: 20286

preg_replace('/[{}\[\]]/', '', $string);

You should add them with proper escaping to class in Regex

 $string = 'asdf{[]a]}ds';
 echo preg_replace('/[{}\[\]]/', '', $string);

Output: asdfads

Upvotes: 1

liyakat
liyakat

Reputation: 11853

As you are looking for a square bracket removal:

$str = preg_replace("/\[([^\[\]]++|(?R))*+\]/", "", $str);

That will convert this:

This [text [more text]] is cool

to this:

This is cool

EDIT

$string = '<p>hey</p><p>[[{"type":"media","view_mode":"media_large","fid":"67","attributes":{"alt":"","class":"media-image","height":"125","typeof":"foaf:Image","width":"125"}}]]</p>';
$new_string = preg_replace('/\[\[.*?\]\]/', '<b>img inserted</b>', $string);

echo $new_string;

let me know if i can help you further.

Upvotes: 0

elclanrs
elclanrs

Reputation: 94121

You'd have to escape it:

/[{}[\]]/

Upvotes: 0

Alex Shesterov
Alex Shesterov

Reputation: 27565

include square brackets (escaped) into the character class: /[{}\[\]]/

Upvotes: 2

Related Questions