Using regular expressions with square brackets

3

Greetings, I have to remove any occurrence of text between brackets. For example:

Eg: [Text in brackets] Text outside brackets. The output would be: "Text outside brackets";

I tried to use the following Regex:

$string = "[Texto entre colchetes] Texto fora do colchetes";
$String = preg_replace("[\/(.*?)\]/",'',$string);
echo $string;

But I did not succeed.

    
asked by anonymous 15.08.2018 / 14:54

3 answers

3

Try this (remove spaces before or after brackets):

$string = "[Texto entre colchetes] Texto fora do colchetes";
$String = preg_replace("\s*\[.*?\]\s*",'',$string);
echo $string;

\s remove whitespace followed by * to get more than one.

\[ and \] escapes the character [ and ] because regex uses it.

The rest is the same as what you entered in the question.

    
15.08.2018 / 15:02
3

Simply deselect the brackets with the escape character ( \ ) and say that one or more occurrences should be replaced with + .

This regular expression will fail in cases where the string is poorly formatted, for example: [texto dentro] texto fora]]]]

$string = "[Texto entre colchetes] Texto fora do colchetes [outro texto] [[asdfasdf]]";
$novo = preg_replace("/\[+[\w\s]+\]+/i",'',$string);
echo $novo;

Result:

Entrda: [Texto entre colchetes] Texto fora do colchetes [outro texto] [[asdfasdf]]
Saída:  Texto fora do colchetes  

Example - ideone

    
15.08.2018 / 15:04
1

Follow the regular expression to solve your problem and use trim () to remove spaces. See an example working here .

$string = "[Texto entre colchetes] Texto fora do colchetes";

echo trim(preg_replace('#\s*\[.+\]\s*#U', ' ', $string));
    
15.08.2018 / 15:00