2012-03-03 6 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

이것은 작업을 수행하는 것 같습니다 (두 번째 예제 사용). 대단히 감사합니다! – 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; 
관련 문제