$re = '/(?: # Non capturing group 1
\G # Matches where the regex engine stops in the previous step
(\w+) # capture group 1: a regex word of 1+ chars
\h* # zero or more horizontal spaces (space, tabs)
(?: # Non capturing group 2
=\h* # literal \'=\' follower by zero or more hspaces
(\w+) # capture group 2: a regex word of 1+ chars
)? # make the non capturing group 2 optional
)+ # repeat the non capturing group 1, one or more/x';
$str = 'Key name = value';
$subst = "\1\2";
$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is ".$result;
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php