簡體   English   中英

PHP-格式化字符串輸出

[英]PHP - Formatting string output

我正在嘗試根據分配給用戶的值來處理文本字符串。

完整的文本字符串是“列表,項目,案例,身份和位置”,並且僅在ADMIN中完整顯示。

系統上的每個用戶都具有訪問權限。 每一項權利決定了他們可以做什么和不能做什么。 因此訪問權限a1 = 'Lists'b1 = 'Items'等...

當用戶登錄頁面時,顯示他們有權訪問的內容。

例如:

Welcome $user
You have access to $foo

對於管理員用戶..這看起來像:

Welcome Admin
You have access to Lists, Items, Cases, Identity and Location

所以現在我正在嘗試執行以下操作:

if ($user == 'admin') $foo = 'Lists, Items, Cases, Identity and Location'; // full access

但是我需要能夠為每個用戶更改值。

$foo ='';
if (strpos($access,'a1') !== false) $foo .= 'Lists ';
if (strpos($access,'b1') !== false) $foo .= 'Items ';
if (strpos($access,'c1') !== false) $foo .= 'Cases ';
if (strpos($access,'d1') !== false) $foo .= 'Identity ';
if (strpos($access,'e1') !== false) $foo .= 'Location ';

我的問題是標點符號混亂。 用戶Miz有權訪問a1,b1,c1

當她登錄時,她得到:

Welcome Miz
You have access to Lists Items Cases

我想說的是:

Welcome Miz
You have access to Lists, Items and Cases

任何人都可以建議實現此目標的最佳方法

謝謝

使用implode()

<?php
$arr = array();

if (strpos($access,'a1') !== false) $arr[] =  'Lists ';
if (strpos($access,'b1') !== false) $arr[] =  'Items ';
if (strpos($access,'c1') !== false) $arr[] =  'Cases ';
if (strpos($access,'d1') !== false) $arr[] =  'Identity ';
if (strpos($access,'e1') !== false) $arr[] =  'Location ';
$last = array_pop($arr);
$foo = count($arr) ? implode(", ", $arr) . " AND " . $last : $last;
?>

嘗試使用數組並加入:

$rights = array();
$foo = '';
if (strpos($access, 'a1') !== false)
    $rights[] = 'Lists ';
if (strpos($access, 'b1') !== false)
    $rights [] = 'Items ';
if (strpos($access, 'c1') !== false)
    $rights [] = 'Cases ';

if (strpos($access, 'd1') !== false && strpos($access, 'e1') !== false) {
    $rights[] = "Identity and Location";
} else {
    if (strpos($access, 'd1') !== false)
        $rights[] = 'Identity ';
    if (strpos($access, 'e1') !== false)
        $rights[] = 'Location ';
}
echo join(', ', $rights);

編輯:基於其他答案中的OP注釋,已處理Identity and Location

這樣的事情會起作用。

$foo ='';
if (strpos($access,'a1') !== false) $foo .= 'Lists, ';
if (strpos($access,'b1') !== false) $foo .= 'Items, ';
if (strpos($access,'c1') !== false) $foo .= 'Cases, ';
if (strpos($access,'d1') !== false) $foo .= 'Identity, ';
if (strpos($access,'e1') !== false) $foo .= 'Location, ';

$str = rtrim($foo,', ');  //remove last ","
echo preg_replace('/,\s([^,]*$)/', ' and $1', $str);  //replace last ", " with " and "

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM