1

我的应用程序要求用户输入他们的公司名称,应用程序将自动创建一个唯一标识符以在 URL 中使用,即

“鲍勃咖啡馆”将成为“鲍勃咖啡馆”

但是如果有重复的名字,我希望应用程序添加一个数字,所以如果已经有一个“bobs-cafe”,我们将使用“bobs-cafe-1”,同样如果已经有一个“bobs-cafe-1”我们将使用“bobs-cafe-2”

我使用了explode,也查看了正则表达式,但我不知道解决这个问题的最佳方法。

我坚持能够抓住数字并增加它并返回字符串

4

3 回答 3

4

添加到 Sarfraz 的答案中,您可能希望使用 LIKE 语句找到它

SELECT `urlIdentifier` FROM `businesses` WHERE `urlIdentifier` LIKE `bobs-cafe%`

这将得到所有的 bobs-cafe 项目 - 这样,如果你得到 5 行,你就知道你有

bobs-cafe
bobs-cafe-1
bobs-cafe-2
bobs-cafe-3
bobs-cafe-4

并且您需要添加 bobs-cafe-5

编辑 - 或者这个:

SELECT count(*)  as `howMany` FROM `businesses` WHERE `urlIdentifier` LIKE `bobs-cafe%`

现在您的结果对象(或数组)将具有总数:

回声 $resultObject->howMany; // 找到的 bobs-cafe sql 数量

于 2010-05-24T07:19:10.130 回答
2

为什么不向 URL 中的每个标识符添加一个自动增量编号?
就像 SO 一样:

stackoverflow.com/questions/ 2895334 /php-application-check-name-is-unique-if-not-append

因此,您拥有唯一标识符和公司名称。

这甚至更好,因为他们可以自由更改其公司名称,而无需更改标识符。

至于你的问题,很简单。仅用于 PHP 实践:

if (/* you've found the name is already non unique and have the max one in the $id */) {
  $parts = explode("-",$id);
  if (isset($parts[1])) $newid = $parts[0]."-".($parts[1]+1);
  else $newid = $parts[0]."-1";
}
于 2010-05-24T07:19:55.630 回答
1

假设$user已经在表格中bobs-cafe

function username_exists ( $user ) {

      $result = mysql_query("SELECT name FROM table WHERE $name LIKE '$user%' ");
      $count = mysql_num_rows($result);

        if ( $result ) {

            $num = $count+1;
            return username_exists ( $user.'-'.$num ) ;

        } else {

            return $user;
        }

}
于 2010-05-24T07:50:58.387 回答