Well, the pattern string is, ultimately, a PHP string literal, so you can use variables just as you would in any other string, e.g.: concatenation, interpolation within a double-quoted or heredoc quoted string, sprintf(), etc. However, you need to be careful about any characters in that string that might have special meaning within a regexp. The preg* set of functions includes the [man]preg_quote/man function, which can be used to escape any such special characters. For instance, say you want to modify the above regex to only allow some user-specified list of allowable characters between the slashes:
$allowedCharacters = 'abcd1234#!%^';
$regexp = '#^/[' . preg_quote($allowedCharacters . '#') . ']+$/#';
if(preg_match($regexp, $string))
{
// valid
}
else
{
// invalid
}