apis17
apis17

Reputation: 2855

php: regex remove bracket in string

similiar like this example, php: remove brackets/contents from a string? i have no idea to replace

$str = '(ABC)some text'

into

$str = 'ABC';

currently use $str = preg_replace('/(.)/','',$str); but not works. how to fix this?

Upvotes: 2

Views: 4036

Answers (4)

Samee
Samee

Reputation: 856

I'd avoid using regex altogether here. Instead, you could use normal string functions like this: $str = str_replace(array('(',')'),array(),$str);

Upvotes: 1

gnarf
gnarf

Reputation: 106412

If you want to use replace, you could use the following:

 $str = "(ABC)some text";
 $str = preg_replace("/^.*\(([^)]*)\).*$/", '$1', $str);

The pattern will match the whole string, and replace it with whatever it found inside the parenthesis

Upvotes: 1

Carsten Gehling
Carsten Gehling

Reputation: 1258

Instead of preg_replace, I would use preg_match:

preg_match('#\(([^)]+)\)#', $str, $m);
echo $m[1];

Upvotes: 2

turbod
turbod

Reputation: 1988

Try this:

$str = preg_replace('/\((.*?)\).*/','\\1',$str);

Upvotes: 0

Related Questions