Sunday, November 20, 2022

[FIXED] How to isolate content until the first double newline sequence?

Issue

<ul>
    <li><a href="#">Foo</a></li>
    <li><a href="#">Foo</a></li>
    <li><a href="#">Foo</a></li>
</ul>

<ul>
    <li><a href="#">Bar</a></li>
    <li><a href="#">Bar</a></li>
    <li><a href="#">Bar</a></li>
</ul>

How can I get any content until the first blank line?

NOTE: First and second part of the content doesn't always start with ul.


Solution

preg_match('/\A.*?(?=\s*^\s*$)/smx', $subject, $regs);
$result = $regs[0];

Explanation

preg_match(
    '/\A    # Start of string
    .*?     # Match any number of characters (as few as possible)
    (?=     # until it is possible to match...
     \s*    #  trailing whitespace, including a linebreak 
     ^      #  Start of line
     \s*    #  optional whitespace
     $      #  End of line
    )       # (End of lookahead assertion)/smx', 
    $subject, $regs);
$result = $regs[0];

assuming that you count lines that contain nothing but whitespace as blank lines. If not, remove the "optional whitespace" line.



Answered By - Tim Pietzcker
Answer Checked By - Cary Denson (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.