Home  >  Article  >  Backend Development  >  How to use regular rules to add navigation directory to articles in PHP

How to use regular rules to add navigation directory to articles in PHP

小云云
小云云Original
2018-03-10 09:47:231540browse

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 = &#39;<h2 class="archt"><strong>我是里面的内容</strong></h2><h2 class="archt2">我是第2个内容</h2><strong>我没有h2包在里面</strong>&#39;;
preg_match_all(&#39;/<h2.*?>.*?(<[^>]+>)?([^<]+)(<\/[^>]+>)?<\/h2>/s&#39;, $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] => 
        )

)

Write it as a function

function article_index($content){  
    $matches = array();   
    $ul_li = &#39;&#39;;    $r = &#39;/<h2.*?>.*?(<[^>]+>)?([^<]+)(<\/[^>]+>)?<\/h2>/s&#39;;    if(preg_match_all($r, $content, $matches))
    {        foreach($matches[2] as $num => $title)
        {            $ul_li .= &#39;<em>&#39;.$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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn