先頭/末尾に余分なスペースを入れたくない場合は、これを試してください。
$str = ':):)test:)test:)test:) :) test:p:) test';
$codes = array(
':)', ':p', // Add smileys here.
);
// We build the $regexp automatically
$regexp = array();
foreach($codes as $smiley)
$regexp[] = preg_quote($smiley, '#');
$regexp = implode('|', $regexp);
// Afterwards, we might replace the above with $regexp = 'VERYCOMPLICATEDSYNTAX';
// Split the string at smileys, trimming the smileys as we go,
// and returning an array of smiley-and-non-smiley parts, except for empty ones
$parts = preg_split("#\s*($regexp)\s*#", $str, -1,
PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
// The new delimiter is a single space.
$str = implode(' ', $parts);
\s
リテラルスペースの代わりに空白マッチャーを使用したことに注意してください。元の文字列に改行がある場合、これは望ましくない結果になる可能性があります。その場合は、\s
" " をリテラル スペース " " に置き換えます。