Regex using preg_replace to separate values according to ")"

Asked

Viewed 181 times

6

I need to use a string separation for the occurrences of closing of parentheses and a space after, with the following technique I managed to do:

preg_replace('/[\)][\s]/', '$0--> $1', '1 () 2 () 3 ()');

exit:

1 () --> 2 () --> 3 ()

I wonder if it is correct or there is a better form of regex '/[\)][\s]/' to catch this occurrence?

1 answer

6


When you just want to pick up a single character, you don’t need the brackets:

preg_replace('/\)\s/', ') --> ', '1 () 2 () 3 ()');

Upshot:

1 () --> 2 () --> 3 ()

The brackets define a character class. Ex: [abc] means "the letter a or the letter b or the letter c" (only one of them).

That’s why, [\)] is the same as \). The same goes for the \s. When you just need to pick up a character, brackets are unnecessary.


In the above case, I am replacing the "closing parentheses followed by space" by ') --> ', and this is the simplest and most direct way.

The way you did it also works, but beyond the brackets there is another detail: you used the variables $0 and $1.

The first ($0) no problem to use, since it corresponds to the whole stretch found by regex (closing parentheses plus space). The second ($1) will be blank because it corresponds to the first catch group. But since your regex has no capture groups, this variable will not be filled and can even be removed. So it would work as well:

preg_replace('/\)\s/', '$0--> ', '1 () 2 () 3 ()');

Just remembering that the \s also matches the character TAB and line breaks (see documentation), in addition to other characters (the exact list may vary from one language to another). If you want to limit your regex to only the blank space, swap the \s by a space:

preg_replace('/\) /', '$0--> ', '1 () 2 () 3 ()');

Or:

preg_replace('/\) /', ') --> ', '1 () 2 () 3 ()');

Notice that there is a gap between the ) and the /.

  • 1

    Very good, thanks for the help, I have to study hard, because work with these functions and regex is very complex, lots of information and details to master!

  • 2

    I was late, right... =)

  • 2

    @Andreicoelho It is, the timing that’s it, right :-)

  • 1

    @Robertcezar Regex is in fact a very broad and complex subject, and it seems to have no end. Two very good sites are that and that, that has interesting tutorials and articles. And 2 books (a little more advanced) are that and that

Browser other questions tagged

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