2012-04-12 96 views
2

對不起,如果這是非常基本的,但我只是學習PHP。在PHP中刪除多個逗號

我有一些代碼,看起來像:

<h4><?=$prop['house_number']?>, <?=$prop['street']?>, <?=$prop['town']?></h4> 

從數據庫如帶回:55,主要街道,townname

當地址不包含街道名稱它回來如:55,鎮名。

我想知道如何刪除commer,所以它只會帶回例如:55,townname。

希望這是一個非常容易的,但我已經嘗試了幾件事情,似乎無法做到正確。

非常感謝

回答

1

您可以使用三元運算符來檢查每個var是否爲空。看看http://davidwalsh.name/php-shorthand-if-else-ternary-operators

代碼會再看看這樣的:在使用

<?php 
    $house_num=($prop['house_number']) ? $prop['house_number'].',' : null; 
    $street=($prop['street']) ? $prop['street'].',' : null; 
    $town=($prop['town']) ? $prop['town'] : null; 
    $h4=$house.' '.$street.' '.$town; 
?> 

然後:

<h4> 
<?=!empty($prop['house_number']) ? $prop['house_number'].', ' : ''?> 
<?=!empty($prop['street']) ? $prop['street'].', ' : ''?> 
<?=!empty($prop['town']) ? $prop['town'].', ' : ''?> 
</h4> 
+0

工作就像一個魅力。我知道這很容易。非常感謝你! – LMR 2012-04-12 19:26:50

2

更換

<?=$prop['street']?>,

<?php if(strlen($prop['street'] > 0) echo $prop['street'] . ", "; ?>

舊代碼輸出的街道名稱,後跟一個逗號,新的代碼檢查,如果街道名長於0個字符,並且只有在輸出時纔會輸出。

3

使用數組來保存值,並implode()

事情是這樣的:

$result = array(); 

if (!empty($prop['house_number']) 
    $result[] = $prop['house_number']; 

if (!empty($prop['street']) 
    $result[] = $prop['street']; 

if (!empty($prop['town']) 
    $result[] = $prop['town']; 

$result = implode(',',$result); 
1

您可以修復你的輸出以後:

ob_start(); 
?> 
<h4><?=$prop['house_number']?>, <?=$prop['street']?>, <?=$prop['town']?></h4> 
<?php 
echo strtr(ob_end_clean(), ', , ', ', '); 

但實際上有百種方式解決它,這只是一個。

echo '<h4>' , implode(', ', array_filter(
     array($prop['house_number'], $prop['street'], $prop['town']), 'strlen') 
    ), '</h4>'; 
2

您可以使用內嵌條件語句,嘗試這種

<h4><?php echo($h4); ?></h4> 
+0

這會給一個額外的尾隨逗號 – xbonez 2012-04-13 14:51:21

+0

只需刪除最後一個逗號,我更新了代碼。 – faino 2012-04-13 16:06:41

1

建議你習慣數組函數和implode;假設你的$支柱陣列看起來像這樣:

$prop = array(
    "house_number" => 55, 
    "street" => "", 
    "town" => "Houston" 
); 

您可以過濾陣列和使用破滅:

function filter_empty($a) { 
    if(strlen(trim($a)) > 0) return(true); 
    return(false); 
} 

$filtered = array_filter($prop, 'filter_empty'); 

從上面,陣列將是這樣的:

print_r($filtered); 
/* 
Array 
(
    [house_number] => 55 
    [town] => Houston 
) 
*/ 

人類可讀的文本行很容易:echo implode(", ", $filtered);

將輸出類似55, Houston - 繞過所有空容器。

0

這只是另一種方式,您可以將地址字符串保存在一個變量中,並用一個逗號替換雙逗號[,,]。類似於hakre正在消耗的想法。

實施例:

<?php $str = $prop['house_number'] . ',' . $prop['street'] . ',' . $prop['town']?> ;?> 
<h4><?=str_replace(',,','',$str);?></h4>