I am trying to convert a multi-line string, to insert line breaks \n after two final closing parenthesis occur in series, ie: )) becomes ))\n.
There is also likely to be a ‘)’ just prior to the ‘))’, effectively creating ‘)))’.
These two or three parenthesis may or may not be “spread out” by indeterminate lengths of whitespace, eg )), ) ), ))), ) ) ), )) ), ) )) and so on.
I’ve tried the following:
//Example message
$message = '(item (name 286) (Index 31) (Image "item001") (class money coin) (code 4 110 0) (country 2) (plural 1) (buy 0))
(item(name 7904)(Index 7904) (specialty (Dex 10(defense 55)(hp 3500)(dodge 71) ))
(item(name 7905)(Index 7905)(country 2)
(level 80)(specialty(hp 3400) ) )
(item(name 7906)(Index 7906)(level 80) (specialty(Str 10)) ) ';
// Converts all lines into one line
$message = preg_replace("/[\r\n]*/","",$message);
// Replace '))' with '))\n' - doesn't work.
$message = preg_replace("/[)s+)]s*/","\n",$message);
$InititemLines = explode("\n", $message);
for ($line = 0; $line < count($InititemLines); $line++) {
echo "Line #<b>{$line}</b> : " . $InititemLines[$line] . "<br />\n";
}
To convert all lines into one, I used:
$message = preg_replace("/[\r\n]*/","",$message);
Then, to replace )) with ))\n, I tried the following (but it doesn’t work):
$message = preg_replace("/[)s+)]s*/","))\n",$message);
I want the output to be like this:
Line #0: (item (name 286) (Index 31) (Image "item001") (class money coin) (code 4 11 0 0) (country 2) (plural 1) (buy 0))
Line #1: (item(name 7904)(Index 7904) (specialty (Dex 10)(defense 55)(hp 3500)(dodge 71) ))
Line #2: (item(name 7905)(Index 7905)(country 2)(level 80)(specialty(hp 3400) ) )
Line #3: (item(name 7906)(Index 7906)(level 80) (specialty(Str 10)) )
This will replace the “))” at the end of ALL lines, in the case of line ending in
)))or)):$message = Preg_replace( "\)?(\s*\)\s*\))", "$1\n", $message );This regex means
\s*\)\s*\)with a pair of ‘(‘ and ‘)’ meaning “group this section, so we can reference it later”. We do this so we can replace it with))\n.And then a more elegant solution might be (depending on your requirements…), to subsequently also strip any excess remaining spaces from before every ‘)’:
$message = preg_replace("(\)\s*)", "\)", $message);This regex means
(In your example, I believe this will strip all the excess whitespace, while leaving the spaces in your strings alone).