Từ bản ckediter 5 chúng ta có thêm chức năng điểm neo có tác dụng rất lớn trong việc tạo ra sự dễ dàng cho người đọc trỏ đến link 1 đoạn viết nhất định đồng thời có lợi cho seo .Các bạn có thể xem 1 link demo sau : https://noithatoneh.com/tu-bep-acrylic/tu-bep-acrylic-mau-trang.html
Vấn đề đặt ra là chúng ta có thể làm sao tạo ra điểm neo như thế 1 cách tự động giúp giảm bớt phần dư thừa khi đăng bài viết
Công cụ ở đây mình dùng ngôn ngữ php và regex để tạo ra điểm neo
/** * Tạo neo tự động * * @access private * @param integer $depth - độ sâu h1,h2,h3... * @param string $html_string - content đầu vào * @return string */ function TableOfContents($depth,$html_string) { //get the headings down to the specified depth $pattern = '/<h[1-'.$depth.']*[^>]*>.*?<\/h[1-'.$depth.']>/'; $whocares = preg_match_all($pattern,$html_string,$winners); //reformat the results to be more usable $heads = implode("\n",$winners[0]); $heads = str_replace('<a name="','<a href="#',$heads); $heads = str_replace('</a>','',$heads); $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $heads = str_replace('id="','href="'.$actual_link.'#' , $heads); $heads = preg_replace('/<h([1-'.$depth.'])>/','<li class="toc$1"> * ',$heads); $heads = preg_replace('/<\/h[1-'.$depth.']>/','</a></li>',$heads); //plug the results into appropriate HTML tags $contents = '<ul>'.$heads.'</ul>'; return $contents; }
Sau đó ta chỉ cần gọi hàm này ra
// tạo bảng neo tự động $tablecontent = TableOfContents(4,$article['content']); $smarty->assign('tablecontent', $tablecontent);
Chi tiết bài viết demo tạo anchor link tự động