-1

i want to ask you something simple. I have string like:

happy (adj)

sad (v)

and i want to replace those brackets with empty string (" ") so it would be like this:

happy

sad

i know that i have to use regex but because im new in regex, can u help me with the pattern guys? thank you :')

Community
  • 1
  • 1
barney
  • 59
  • 1
  • 7
  • Possible duplicate of [php: remove brackets/contents from a string?](http://stackoverflow.com/questions/1336672/php-remove-brackets-contents-from-a-string) or [Remove Text Between Parentheses PHP](http://stackoverflow.com/questions/2174362/remove-text-between-parentheses-php). – bobble bubble Jun 27 '16 at 07:45

1 Answers1

3

The ( and ) will need to be escaped. . is any character and * is zero or more occurrences of the previous character/grop; +is one or more. So put that together with delimiters and you have:

<?php
echo preg_replace('/\(.*?\)/', '', 'happy (adj)

sad (v)');

Note the ? as well that takes away the greediness of the * quantifier, http://www.regular-expressions.info/possessive.html.

Regex Demo: https://regex101.com/r/zQ5bW1/2
PHP Demo: https://eval.in/595919

or you could use a negated character class to find the closing ).

echo preg_replace('/\([^)]+\)/', '', 'happy (adj)

sad (v)');

Alternative regex demo: https://regex101.com/r/zQ5bW1/3

chris85
  • 23,846
  • 7
  • 34
  • 51
  • I think the space before the bracket should be removed also. – Akam Jun 27 '16 at 02:14
  • Not sure if that is OPs intention or not. Here are approaches though if it is, https://regex101.com/r/zQ5bW1/4 or https://regex101.com/r/zQ5bW1/5 – chris85 Jun 27 '16 at 02:16