在PHP中添加字符和特殊符号之间的空格

I am newbie of php, i want to know how to add whitespace between character and symbol or symbol and symbol, for example, the original string is “[PDF format(29.71MB)]“, how can i use function preg_replace or other method to represent the result as “[ PDF format (29.71MB) ]“? i.e, I want to leave the space between symbol "[" and character "P" and also ")" and "]"

Many thanks

Simon

For your string, regular expression looks a bit like too much to me:

$string = '[PDF format(29.71MB)]';
$string = str_replace(array('[', ']', '('), array('[ ', ' ]', ' ('), $string);

This replaces the chars that demand additional spaces with their variant with space.

$s = "[PDF format(29.71MB)]";

$s = preg_replace("/[\[)](?!\s)/", "$0 ", $s);
$s = preg_replace("/(?!<\s)[\[(]/", " $0", $s);
$s = trim($s);

echo $s;

The two regular expressions

  1. append a space to every [ or ) that is not already followed by a space
  2. prepend a space to every ] or ( that is not already preceded by a space

See: http://ideone.com/No9dq

$s = "[PDF format(29.71MB)]";
$s = preg_replace("/([^\w.])/", " \\1 ", $s);
$s = preg_replace("/\s\s+/", " ", $s);
echo $s;

The first puts a space at each side of not a word character and not a dot. The second removes redundant whitespace.