我尝试使用str_replace来替换''我已经使用了下面的代码,但它并没有取代任何内容:
\ n \ n&#39;电话&#39;<?php
$start_up = str_replace('','phone','start_up');
$sales = str_replace('','phone','');
$resourcing = str_replace('','phone','resourcing');
$management = str_replace('','phone','');
$array = "($start_up OR $sales OR $resourcing OR $management)";
echo $array;
?>
我想要这个:
(start_up OR phone OR resourcing OR phone)
但相反它是这样做的:
(start_up OR OR resourcing OR )
我知道我可以使用!isset($ var)类型的查询,但这看起来很笨拙且冗长。有没有办法在str_replace查询中包含空字符串?
答案 0 :(得分:0)
您可以使用preg_replace
代替str_replace
:
$start_up = preg_replace('/^$/','phone','start_up');
$sales = preg_replace('/^$/', 'phone', '');
$resourcing = preg_replace('/^$/','phone','resourcing');
$management = preg_replace('/^$/','phone','');
$array = "($start_up OR $sales OR $resourcing OR $management)";
echo $array;
输出:
(start_up OR phone OR resourcing OR phone)
它将替换为phone
的空字符串。
修改或者您可以使用empty()
和ternary operator:
$start_up = empty('start_up') ? 'phone' : 'start_up';
$sales = empty('') ? 'phone' : '';
$resourcing = empty('resourcing') ?'phone' : 'resourcing';
$management = empty('') ? 'phone' : '';
$array = "($start_up OR $sales OR $resourcing OR $management)";
echo $array;
输出与上述相同。