输出PHP条件为字符串,删除最后一个字符

时间:2012-05-10 14:00:02

标签: php string conditional substr

我正在使用wordpress的高级自定义字段,它使用语法get_field('custom_field_name');从数据库中提取自定义字段。在这种情况下,我有一系列的复选框,我使用PHP来查看是否已经检查过每一个,如果是,它会吐出一个字符串。这是我的PHP:

<?php 
    if(in_array('brand-id', get_field('type_of_work') )): echo "<a href='../../work/#brand-id'>Brand ID</a> |"; endif; echo " ";

    if(in_array('print', get_field('type_of_work') )): echo "<a href='../../work/#print'>Print</a> |"; endif; echo " ";

    if(in_array('books', get_field('type_of_work') )): echo "<a href='../../work/#books'>Books</a> |"; endif; echo " ";

    if(in_array('web', get_field('type_of_work') )): echo "<a href='../../work/#web'>Web</a> |"; endif; echo " "; 

    if(in_array('packaging', get_field('type_of_work') )): echo "<a href='../../work/#packaging'>Packaging</a> |"; endif; echo " ";

    if(in_array('exhibit', get_field('type_of_work') )): echo "<a href='../../work/#exhibit'>Exhibit</a> |"; endif; 

?>

这是做什么的,如果选中此复选框,则吐出该复选框的链接。如你所见,我呼应“|”每个链接后。问题是最后一个链接后跟一个“|”。我想删除最后一个“|”以编程方式使用PHP。也许我可以将整个事物转换为字符串,然后使用substr($string, 0, -1);? Anny想法我会怎么做呢?

3 个答案:

答案 0 :(得分:2)

$links = array();

if(in_array('brand-id', get_field('type_of_work') )) $links[] = "<a href='../../work/#brand-id'>Brand ID</a>";
....

echo implode(" | ",$links);

答案 1 :(得分:1)

使用字符串:

$checks = "";

if(in_array('brand-id', get_field('type_of_work') )):  $checks .= "<a href='../../work/#brand-id'>Brand ID</a> | "; endif;

if(in_array('brand-id', get_field('type_of_work') )):  $checks .= "<a href='../../work/#print'>Print</a> |"; endif;

然后:$ check上的substr():echo substr($checks, 0, -2);

答案 2 :(得分:0)

  1. 而不是直接回显文本,将其连接到字符串变量
  2. 使用trim($string, '|')删除尾随管|manual