Home > Article > Backend Development > How to use regular rules to add navigation directory to articles in PHP
There may be many children who are interested in directory navigation. Click on the directory text above to quickly jump to related content, which is suitable for long articles or articles with special needs. Through regular expressions, the article content automatically extracts text with H2 tags for directory indexing.
$str = '<h2 class="archt"><strong>我是里面的内容</strong></h2><h2 class="archt2">我是第2个内容</h2><strong>我没有h2包在里面</strong>'; preg_match_all('/<h2.*?>.*?(<[^>]+>)?([^<]+)(<\/[^>]+>)?<\/h2>/s', $str, $arr); print_r($arr);
Array( [0] => Array ( [0] => <h2 class="archt"> <strong>我是里面的内容</strong></h2> [1] => <h2 class="archt2">我是第2个内容</h2> ) [1] => Array ( [0] => <strong> [1] => ) [2] => Array ( [0] => 我是里面的内容 [1] => 我是第2个内容 ) [3] => Array ( [0] => </strong> [1] => ) )
function article_index($content){ $matches = array(); $ul_li = ''; $r = '/<h2.*?>.*?(<[^>]+>)?([^<]+)(<\/[^>]+>)?<\/h2>/s'; if(preg_match_all($r, $content, $matches)) { foreach($matches[2] as $num => $title) { $ul_li .= '<em>'.$title." </em>"; } } return $ul_li; }
Related recommendations:
JavaScript implements the starry navigation bar
in vue How to make the bottom navigation TabBar on the homepage
css3 to achieve the mouse following navigation effect
The above is the detailed content of How to use regular rules to add navigation directory to articles in PHP. For more information, please follow other related articles on the PHP Chinese website!