创建独特的页面标题slugs php

前端之家收集整理的这篇文章主要介绍了创建独特的页面标题slugs php前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个功能,为页面标题创建独特的slug.它会检查页面表中的slug是否可用,然后通过相应地添加’-int’来创建一个独特的slug.该函数对前三个条目工作正常,例如,三次输入的’test slug’将创建’test-slug-1′,’test-slug-2’和’test-slug-3′.然后,我得到第四个条目的错误“致命错误:超过30秒的最大执行时间”.逻辑应该有一些问题,任何人都可以帮我找到它.Below是代码
function createSlug($title,$table_name,$field_name) {

global $db_connect;

$slug = preg_replace("/-$/","",preg_replace('/[^a-z0-9]+/i',"-",strtolower($title)));

$counter = 1;

do{

  $query = "SELECT * FROM $table_name WHERE  $field_name  = '".$slug."'";
  $result = MysqLi_query($db_connect,$query) or die(MysqLi_error($db_connect));


  if(MysqLi_num_rows($result) > 0){
      $count = strrchr($slug,"-"); 
      $count = str_replace("-",$count);
      if($count > 0){

          $length = count($count) + 1;
          $newSlug = str_replace(strrchr($slug,"-"),'',$slug);
          $slug = $newSlug.'-'.$length;

          $count++;

      }else{
          $slug = $slug.'-'.$counter;
      }  

  }

  $counter++; 
  $row = MysqLi_fetch_assoc($result);

}while(MysqLi_num_rows($result) > 0);

return $slug;

}

只需使用一个查询即可为您完成所有繁重的工作……
$slug = preg_replace("/-$/",strtolower($title)));

$query = "SELECT COUNT(*) AS NumHits FROM $table_name WHERE  $field_name  LIKE '$slug%'";
$result = MysqLi_query($db_connect,$query) or die(MysqLi_error($db_connect));
$row = $result->fetch_assoc();
$numHits = $row['NumHits'];

return ($numHits > 0) ? ($slug . '-' . $numHits) : $slug;
原文链接:https://www.f2er.com/php/137156.html

猜你在找的PHP相关文章