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 /
.
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!
– user78859
I was late, right... =)
– Andrei Coelho
@Andreicoelho It is, the timing that’s it, right :-)
– hkotsubo
@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
– hkotsubo