如果行开头,Php不打印

时间:2011-05-23 19:48:33

标签: php

我有以下代码,只要行不为空,就会打印出文本行:

$textChunk = wordwrap($value, 35, "\n");
    foreach(explode("\n", $textChunk) as $textLine)
    {
        if ($textLine!=='') 
        {
            $page->drawText(strip_tags(ltrim($textLine)), 75, $line, 'UTF-8');
            $line -=14;
        }
    }

我想编辑它,如果它以'T:'开头也不打印该行

有什么想法吗?

4 个答案:

答案 0 :(得分:4)

使用substr检查前两个字符:

if ($textLine !== '' && substr($textline, 0, 2) !== 'T:')

答案 1 :(得分:0)

您可以在strpos()位置使用0寻找“T:”:

$textChunk = wordwrap($value, 35, "\n");
foreach(explode("\n", $textChunk) as $textLine)
{
    // Don't print if T: is at the 0 position
    if (strpos($textLine, "T:") > 0) 
    {
        $page->drawText(strip_tags(ltrim($textLine)), 75, $line, 'UTF-8');
        $line -=14;
    }
}

如果您仍需要过滤空白,请使用:

        if ($textLine !== "" || strpos($textLine, "T:") > 0) 

答案 2 :(得分:0)

$textChunk = wordwrap($value, 35, "\n");
foreach(array_filter(explode("\n", $textChunk)) as $textLine)
{
    if (strncmp('T:', $textLine,2) !== 0)
    {
        $page->drawText(strip_tags(ltrim($textLine)), 75, $line, 'UTF-8');
        $line -=14;
    }
}

完全strncmp()substr()略快。

答案 3 :(得分:0)

我经常发现自己编写这样的函数来处理字符串的开始/结束

function stringStartsWith($haystack, $needle) {
    return $needle === substr($haystack, 0, strlen($needle));
 }

function stringEndsWith($haystack, $needle) {
    return $needle === substr($haystack,-1 *strlen($needle));
}

然后你可以使用

if (textLine && ! stringStartsWith($textLine,'T:')