Php don't print if line begins with
I have the below code which prints out lines of text as long as the lines a开发者_运维问答ren't empty:
$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;
}
}
I would like to edit it so that it also doesn't print the line if it begins with 'T:'
Any ideas?
Use substr to check the first two characters:
if ($textLine !== '' && substr($textline, 0, 2) !== 'T:')
You can use strpos()
looking for "T:" in the 0
position:
$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 you still need to filter the blanks as well, use:
if ($textLine !== "" || strpos($textLine, "T:") > 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;
}
}
At all strncmp()
is slightly faster than substr()
.
I often find myself writing such functions to deal with starting/ending of strings
function stringStartsWith($haystack, $needle) {
return $needle === substr($haystack, 0, strlen($needle));
}
function stringEndsWith($haystack, $needle) {
return $needle === substr($haystack,-1 *strlen($needle));
}
Then you could use
if (textLine && ! stringStartsWith($textLine,'T:')
精彩评论