Using regular expressions with square brackets

Asked

Viewed 277 times

3

Greetings, I have to remove any occurrence of texts between brackets. As for example:

Ex.: [Text in square brackets] Text out of square brackets. Output would be: "Text out of square brackets";

I tried using the following Regex:

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

But I was unsuccessful.

  • 3

    Brackets are part of the construction of a regular expression. If you want to have it in string, you will need to escape them.

3 answers

3

Try this (remove spaces before or after square brackets):

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

\s removes blanks followed by * to catch more than one.

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

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

3

Just undo 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 badly 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;

Upshot:

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

Example - ideone

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));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.