与其问“我该如何解决这个问题?”,不如先问“我为什么会遇到这个问题?”
$user = "< img src='default.jpg' />John";
是< img src='default.jpg' />John
用户名吗?你为什么用它作为一个?我猜这背后有一些聪明的想法,比如“好吧,我总是用他们的名字来显示用户的图片,所以我只会让图片成为他们名字的一部分。这会导致比它解决的问题更多的问题。这回到计算机科学中一个叫做关注点分离的大概念。图像在逻辑上不是用户名的一部分,所以不要将它存储为一个。如果你总是一起显示它们,你可以使用函数来显示用户的以标准方式获取信息,而无需将图像作为用户名的一部分。
所以首先,从名称中删除图像。有几种方法可以单独存储它。
我建议使用一个类:
class User {
public $name;
public $imageSource;
// The following functions are optional, but show how a class
// can be useful.
/**
* Create a user with the given name and URL to their image
*/
function __construct($name, $imageSource) {
$this->name = $name;
$this->imageSource = $imageSource;
}
/**
* Gets the HTML to display a user's image
*/
function image() {
return "<img src='". $this->imageSource ."' />";
}
/**
* Gets HTML to display to identify a user (including image)
*/
function display() {
return $this->image() . $this->name;
}
}
$user = new User("john", "default.jpg");
// or without the constructor defined
//$user = new User();
//$user->name = "john";
//$user->imageSource = "default.jpg";
echo $user->display();
如果你想更懒一点,你可以使用“数组”,但我不建议在一般情况下使用它,因为你失去了类的酷特性(比如那些函数):
$user = array(
name => "john",
image => "<img src='default.jpg' />";
);
echo $user["image"] . $user["name"];
在您的数据库中(如果您使用的是一个),将它们分开列,然后使用上述数据结构之一。
现在你有了这个,很容易使用foreach 循环查看用户名是否在给定列表中:
function userNameInList($user, $users) {
for($users as $current) {
if($user->name == $current) {
return true;
}
}
return false;
}
$newUser = new User("John", "john.jpg");
$currentUsers = array("John", "Mary", "Bob");
if(userNameInList($newUser, $currentUsers) {
echo "Sorry, user name " . $newUser->name . " is already in use!";
}
如果您是 PHP 新手,正常for
循环可能更容易理解:
function userNameInList($user, $users) {
for($i = 0; $i < count($users); ++i) {
$current = $users[$i];
if($user->name == $current) {
return true;
}
}
return false;
}
让我知道如果其中任何一个不运行,我不再经常编写 PHP 了..