You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 = " &lt;h2&gt;1page&lt;/h2&gt;&lt;p&gt;...&lt;/p&gt; &lt;!--nextpage--&gt; &lt;h2&gt;2page&lt;/h2&gt;&lt;p&gt;...&lt;/p&gt; &lt;!--nextpage--&gt; &lt;h2&gt;3page&lt;/h2&gt;&lt;p&gt;...&lt;/p&gt; &lt;!--nextpage--&gt; &lt;h2&gt;4page&lt;/h2&gt;&lt;p&gt;...&lt;/p&gt; &lt;!--nextpage--&gt; &lt;h2&gt;5page&lt;/h2&gt;&lt;p&gt;...&lt;/p&gt; ";

// Split the content at each nextpage separator
$pageParts = preg_split('/\s*&lt;!--nextpage--&gt;\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 . '&lt;!--nextpage--&gt;';
    } 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)(&lt;h2&gt;.*?&lt;\/p&gt;\s*&lt;!--nextpage--&gt;)|(&lt;h2&gt;.*?&lt;\/p&gt;)\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 = " &lt;h2&gt;1page&lt;/h2&gt;&lt;p&gt;...&lt;/p&gt; &lt;!--nextpage--&gt; &lt;h2&gt;2page&lt;/h2&gt;&lt;p&gt;...&lt;/p&gt; &lt;!--nextpage--&gt; &lt;h2&gt;3page&lt;/h2&gt;&lt;p&gt;...&lt;/p&gt; &lt;!--nextpage--&gt; &lt;h2&gt;4page&lt;/h2&gt;&lt;p&gt;...&lt;/p&gt; &lt;!--nextpage--&gt; &lt;h2&gt;5page&lt;/h2&gt;&lt;p&gt;...&lt;/p&gt; ";

// Split and capture both content and separators
$matches2 = preg_split(
    '/(\s*&lt;!--nextpage--&gt;\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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:44:33