Hi,
A possibility would be to use the 'e
' regex-modifier, to call, for instance, the trim
function on the string.
Quoting that page of the manual :
e (PREG_REPLACE_EVAL
)
If this modifier is set, preg_replace()
does normal substitution of
backreferences in the replacement
string, evaluates it as PHP code, and
uses the result for replacing the
search string. Single quotes, double
quotes, backslashes (\
) and NULL
chars will be escaped by backslashes
in substituted backreferences.
Only preg_replace()
uses this
modifier; it is ignored by other PCRE
functions.
For instance, this code, only slightly different from yours :
$bbCode = <<<STR
[quote]
Hello World
[/quote]
STR;
$output = preg_replace("/\[quote\](.+?)\[\/quote\]/es", "'<blockquote>' . trim('\\1') . '</blockquote>'", $bbCode);
var_dump($output);
Would give you :
string '<blockquote>Hello World</blockquote>' (length=36)
ie, the trim
function is called on what was matched -- note it will remove all white-spaces at the beginning and end of your string ; not only newlines, but also spaces and tabulations.
(For instance, you can take a look at Example #4 on the manual page of preg_replace
)
(It's maybe a bit overkill in this case, should I add -- but it's nice to know anyway)