PHP if else语句产生不需要的换行符

时间:2015-12-11 11:52:04

标签: php if-statement line-breaks

我正在使用PHP if else语句忽略自定义字段'thingstodo',如果它是空的。我有以下代码可以工作,但它在我的内容中的每个段落标记之后放置了不需要的换行符。我哪里错了?

<?php if (get_field('gettingthere')): ?>
    <div class="inprofile3col">
        <h2>Getting there</h2>
        <span class="content">
            <?php echo get_post_meta($post->ID, 'gettingthere', true); ?>
        </span>
    <?php endif; ?>
    <!-- ends Getting there -->
    <!-- Things to do begins -->
    <?php if (get_field('thingstodo')): ?> 
        <h2>Things to do</h2>
    <?php endif; ?>
    <span class="content">
        <?php
        $value = get_field('thingstodo');
        if ($value) {
            echo $value;
        } else {
            echo '';
        }
        ?>
    </span>
</div>

2 个答案:

答案 0 :(得分:0)

下面

<span class="content">
<?php 
$value = get_field('thingstodo');
if ($value ) {echo $value ;} else {echo '';}
?>
</span>

如果字段为空,您仍然有输出:空的span-tag:

<span class="content">
echo '';
</span>

答案 1 :(得分:0)

您应该从thingstodo中删除换行符并避免使用空的html标记。这是更新后的标记:

   <?php if( get_field('gettingthere') ): ?>
    <div class="inprofile3col">
    <h2>Getting there</h2>
    <span class="content">
    <?php echo get_post_meta( $post->ID, 'gettingthere', true ) ; ?>
    </span>
    <?php endif; ?>
    <!-- ends Getting there -->
    <!-- Things to do begins -->
    <?php if( get_field('thingstodo') && !empty(trim(get_field('thingstodo')))) { ?> 
    <h2>Things to do</h2>
    <span class="content">
    <?php 
    $value = preg_replace('/\s\s+/',' ',trim(get_field('thingstodo')));    
    if ($value) {echo $value ;} else {echo '';}
    ?>
    </span>
    <?php } ?>
    </div>