PHP正则表达式实现按WordPress<!--nextpage-->分割内容
Hey there! Let's work through this regex problem for your PHP 7.1 setup. Here are straightforward solutions for both of the array formats you're targeting:
This format groups each page's content with its following <!--nextpage--> tag (the last entry only has the page content). Instead of a complex regex match, splitting the string first and then modifying the parts is often more readable:
$the_content = " <h2>1page</h2><p>...</p> <!--nextpage--> <h2>2page</h2><p>...</p> <!--nextpage--> <h2>3page</h2><p>...</p> <!--nextpage--> <h2>4page</h2><p>...</p> <!--nextpage--> <h2>5page</h2><p>...</p> "; // Split the content at each nextpage separator $pageParts = preg_split('/\s*<!--nextpage-->\s*/', trim($the_content)); // Build the desired array $matches1 = []; foreach ($pageParts as $index => $part) { if ($index < count($pageParts) - 1) { // Add the separator back to all except the last part $matches1[] = $part . '<!--nextpage-->'; } else { $matches1[] = $part; } } print_r($matches1);
If you prefer a regex match approach instead, you can use this preg_match_all pattern to capture each block directly:
preg_match_all('/(?s)(<h2>.*?<\/p>\s*<!--nextpage-->)|(<h2>.*?<\/p>)\s*$/', $the_content, $matches); $matches1 = array_merge(array_filter($matches[1]), array_filter($matches[2])); print_r($matches1);
For this format, we'll use preg_split with the PREG_SPLIT_DELIM_CAPTURE flag—this lets us capture the separators alongside the page content, resulting in the alternating array you want:
$the_content = " <h2>1page</h2><p>...</p> <!--nextpage--> <h2>2page</h2><p>...</p> <!--nextpage--> <h2>3page</h2><p>...</p> <!--nextpage--> <h2>4page</h2><p>...</p> <!--nextpage--> <h2>5page</h2><p>...</p> "; // Split and capture both content and separators $matches2 = preg_split( '/(\s*<!--nextpage-->\s*)/', trim($the_content), -1, PREG_SPLIT_DELIM_CAPTURE ); // Clean up empty elements and reindex the array $matches2 = array_values(array_filter($matches2, function($item) { return trim($item) !== ''; })); print_r($matches2);
The PREG_SPLIT_DELIM_CAPTURE flag tells PHP to include the matched separators (the part in parentheses) in the output array, which gives us that alternating content-separator structure.
内容的提问来源于stack exchange,提问作者kbash

