如果问题是“我能不用冒号和空引号吗?”答案是否定的,你必须要有闭合的
:''
,最好使用括号来明确你的意愿。
$var = 'here is the first part and '.
(( $foo == $bar ) ? "the optional middle part":'') .
' and the rest of the string.'
我认为这里最大的问题是你试图在行内完成操作。这基本上归结为相同的过程,不使用未关闭的三元运算符:
$var = 'here is the first part and ';
if( $foo == $bar ) $var .= "the optional middle part";
$var .= ' and the rest of the string.';
这是另一种实现相同目标的方法,无需担心条件语句破坏字符串:
$middle = '';
if( $foo == $bar ) $middle = ' the optional middle part and';
$var = sprintf('here is the first part and%s the rest of the string.',$middle);
现在,如果你想要过于聪明地做这件事情,我想你可以尝试这样做:
$arr = array('here is the first part and',
'',
'here is the end');
$arr[$foo == $bar] = 'here is the middle and';
$var = implode(' ', array_filter($arr));
:
的情况下使用三元运算符。为什么你不想使用它呢? - Marko D