2012-03-03 7 views
1

のは文字列がすでに存在するかどうかを確認し、最後に+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構造のためのユニークなナメクジを作成するために、これをやりたいです。

ありがとうございました。

+0

ここで 'dbrows($ query)'とは何ですか? –

+0

これはちょうどmysql_num_rows関数です – m3tsys

答えて

8

私はあなたにCodeigniter'sincrement_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; 
} 

がそれに番号を付加したり 数を増加させることにより、文字列をインクリメントします。ユニークなタイトルやスラッグを持つ「コピー」やファイルの作成、データベースの複製に役立ちます。

使用例:もちろん

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

これは仕事をしているようです(2番目の例を使用)。どうもありがとうございました! – m3tsys

+0

私のものではないコードを貼り付けるのは少し面倒ですが、うまくいきました。 –

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; 
関連する問題