让我说我检查是否
$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...
}
我想这样做可以为更友好的网址结构创建独特的slu ..
感谢。
答案 0 :(得分:8)
我可以为您提供Codeigniter's increment_string()
功能的来源:
/**
* 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;
}
通过向其附加数字或增加字符串来增加字符串 数。用于创建“副本”或文件或复制数据库 内容具有独特的标题或slu ..
用法示例:
echo increment_string('file', '_'); // "file_1" echo increment_string('file', '-', 2); // "file-2" echo increment_string('file-4'); // "file-5"
答案 1 :(得分:2)
$str = "some-string-that-might-end-in-a-number";
$strLen = strlen($str);
//check the last character of the string for number
if(intval($str[$strLen-1])>0)
{
//Now we replace the last number with the number+1
$newNumber = intval($str[$strLen-1]) +1;
$str = substr($str, 0, -1).$newNumber;
}
else
{
//Now we append a number to the end;
$str .= "-1";
}
当然这个限制是它只能得到最后一位数......如果这个数字是10怎么办?
$str = "some-string-that-might-end-in-a-number";
$strLen = strlen($str);
$numberOfDigits = 0;
for($i=$strLen-1; $i>0; $i--)
{
if(intval($str[$i])==0)
{
$numberOfDigits = $strLen-($i-1);
break;
}
}
//Now lets do the digit modification
$newNumber = 0;
for($i=1; $i<=$numberOfDigits; $i++)
{
$newNumber += intval($str[$strLen-$i])*((10*$i)-10));
}
if($newNumber == 0)
{ $newNumber = 1; }
$newStr = "-{$newNumber}";
//Now lets add the new string to the old one
$str = substr($str, 0, ($numberOfDigits*-1)).$newNumber;