本文介绍了如何检查字符串是否已经存在以及它是否在末尾添加+1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我要检查

$strig = "red-hot-chili-peppers-californication";

我的数据库中已经存在

$query = dbquery("SELECT * FROM `videos` WHERE `slug` = '".$strig."';");
$checkvideo = dbrows($query);
if($checkvideo == 1){

// the code to be executed to rename $strig
// to "red-hot-chili-peppers-californication-2"
// it would be great to work even if $string is defined as
// "red-hot-chili-peppers-californication-2"  and
// rename $string to "red-hot-chili-peppers-californication-3"  and so on...

}

我想这样做是为了创建更独特的子弹头,以获得更友好的url结构.

I want to do this to create unique slugs for a more friendly url structure.

谢谢.

推荐答案

我可以为您提供 Codeigniter的 increment_string()函数:

I can offer you the source of Codeigniter's increment_string() function:

/**
 * CodeIgniter String Helpers
 *
 * @package     CodeIgniter
 * @subpackage  Helpers
 * @category    Helpers
 * @author      ExpressionEngine Dev Team
 * @link        http://codeigniter.com/user_guide/helpers/string_helper.html
 */

/**
 * Add's _1 to a string or increment the ending number to allow _2, _3, etc
 *
 * @param   string  $str  required
 * @param   string  $separator  What should the duplicate number be appended with
 * @param   string  $first  Which number should be used for the first dupe increment
 * @return  string
 */
function increment_string($str, $separator = '_', $first = 1)
{
    preg_match('/(.+)'.$separator.'([0-9]+)$/', $str, $match);

    return isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $str.$separator.$first;
}

用法示例:

echo increment_string('file', '_'); // "file_1"
echo increment_string('file', '-', 2); // "file-2"
echo increment_string('file-4'); // "file-5"

这篇关于如何检查字符串是否已经存在以及它是否在末尾添加+1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:49
查看更多