PHP How to remove lines that are less than 6 characters
I am sorting through some lines and some contain email, some don't.
I need to remove all lines less than 6 characters.
I did a little surfing and found no solid answers so, I tried to write my first expression.
Please tell me if this will w开发者_开发知识库ork. Did I get it right?
$six-or-more = preg_replace("!\b\w{1,5}\b!", "", $line-in);
Followed by the below which I "stole" which may in fact be superfluous.
$no-empty-lines = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $six-or-more);
$lines = preg_split("/[\s]*[\n][\s]*/", $no-empty-lines);
You can see what I am trying to do but, I think it is a bit much.
Thanks for the tutorial.
You can use strlen()
or mb_strlen()
(for multibyte string) for check line lenght.
\b
matches a "word boundary" -- that is, the start or end of a word. It'll trigger on spaces and punctuation between words as well, so you'll effectively remove every word between 1 and 5 chars, rather than every line as intended. (BTW, if you have backslashes in strings, you should either be escaping them or using single-quotes instead to avoid future gotchas.)
You could try
$six_or_more = preg_replace('/^.{0,5}$[\r\n]*/m', '', $line_in);
With the /m
modifier, ^
and $
match the start and end of each line, respectively, rather than the start and end of the whole string. It matches right before the newline, though, so the line would more than likely become blank rather than getting removed unless you match the newline "after the end" as well.
lets say that your lines are in array:
$lines= array('less', 'name', 'some long name', 'my.email@email.email');
and you want that all longer than 6 characters are printed out...
<?php
$lines= array('less', 'name', 'some long name', 'my.email@email.email');
foreach ($lines as $line) {
if(strlen($line) < 6) { //this chect if string length is higher of 5
continue; //if not skip
}
else {
echo $line . '<br />'; //print line or do what you want :)
}
}
?>
The above example will output:
some long name
my.email@email.email
Why not explode the data at a new line, check if individual line length is less than 6. If its less, expunge the line, if not, proceed.
精彩评论