开发者

How to detect more than one line break \n in PHP?

I need to detect more than one \n. Doesn't matter if it's 2 or 1000, as long as it's more than one \n. What would be the regex for this (if regex is necessary that is)?

EDIT

I am using this:

$pregmatch = 开发者_高级运维preg_match('#\\n\\n+#', $locations);
if ($pregmatch > 0) {
    echo 'more than one, this many: '.count($pregmatch);
} else
        echo 'less than one';

but count($pregmatch) doesn't return the actual number of more than one \n detected. How can that be achieved?


Are you looking for more than 1 \n in general? if so:

if (preg_match_all('#\\n#', $string, $matches) > 1) {
    //More than 1 \n
}

Or without regex:

if (substr_count($string, "\n") > 1) {
    //More than 1 \n
}

Or even (but it's far less efficient):

$chars = count_chars($string);
if (isset($chars[ord("\n")]) && $chars[ord("\n")] > 1) {
    //More than 1 \n
}

If in a row:

if (preg_match_all('#\\n\\n+#', $string, $matches) > 0) {
    //More than 1 \\n in a row
}

Edit: So, based on your edit, I can summize two possibilities about what you want to know.

If you want to know the number of \n characters in a row (more than 1), you could do:

if (preg_match('#\\n\\n+#', $string, $match)) {
    echo strlen($match[0]) . ' Consecutive \\n Characters Found!';
}

Or, if you wanted to know for each occurance:

if (preg_match_all('#\\n\\n+#', $string, $matches)) {
    echo count($matches) . ' Total \\n\\n+ Matches Found';
    foreach ($matches[0] as $key => $match) {
        echo 'Match ' . $key . ' Has ' . 
            strlen($match) . ' Consecutive \\n Characters Found!';
    }
}


Something like (doc):

preg_match_all("[\n]*", $yourString, $outArray)

preg_match_all will return a count of how many there were, as well as the matches in the outArray.


You need to provide the /m modifier so that the scan spans more than on line:

if (preg_match('/\n\n/m', $str)) {
    echo "match";
} else {
    echo "no match";
}


You can avoid using regex, saving CPU, here is an elegant and tricky way:

$text_parts = explode("\n", $original_string);

Now you can join it replacing line breaks with something elese:

$new_string = implode("<br />", $text_parts);

I hope this helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜