2

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?

1
  • all works! which one should i choose? which is the best answer? Commented Jun 14, 2010 at 6:42

4 Answers 4

2

Instead of preg_replace, I would use preg_match:

preg_match('#\(([^)]+)\)#', $str, $m);
echo $m[1];
Sign up to request clarification or add additional context in comments.

2 Comments

Realistically, this is a more clear cut case for matching on a string rather than replacing a string.
Welcome to Stack Overflow! Start each line with 4 spaces to format it as code - stackoverflow.com/editing-help . Also,there's no need to sign your post.
1

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

Comments

1

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

1 Comment

thanks user366075, but this not remove some text at the end of bracket. only wants string in bracket and remove others.
0

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.