php如何判断两个字符串相同
时间: 2023-11-29 21:03:53 浏览: 29
在 PHP 中,可以使用 `strcmp` 函数来比较两个字符串是否相同。`strcmp` 函数返回一个整数,如果两个字符串相等则返回 0,如果第一个字符串小于第二个字符串则返回小于 0 的值,如果第一个字符串大于第二个字符串则返回大于 0 的值。以下是 `strcmp` 函数的使用示例:
```php
$str1 = "Hello";
$str2 = "hello";
if (strcmp($str1, $str2) == 0) {
echo "两个字符串相同";
} else {
echo "两个字符串不相同";
}
```
在上面的示例中,`strcmp` 函数将 `str1` 和 `str2` 作为参数进行比较,如果两个字符串相等,则输出 "两个字符串相同",否则输出 "两个字符串不相同"。
相关问题
php 字符串判断是否相同
在 PHP 中,可以使用比较运算符 "==" 来判断两个字符串是否相同。例如:
```
$str1 = "hello";
$str2 = "world";
if ($str1 == $str2) {
echo "The two strings are the same.";
} else {
echo "The two strings are different.";
}
```
也可以使用 "===" 判断两个字符串是否完全相同,包括类型和值。
```
$str1 = "123";
$str2 = "123";
if ($str1 === $str2) {
echo "The two strings are the same.";
} else {
echo "The two strings are different.";
}
```
还可以使用strcmp()或strcasecmp()函数来比较字符串是否相同,但是函数需要返回值判断,如果返回值为0,说明字符串相同,如果返回值为负数或正数则说明不同。
```
$str1 = "hello";
$str2 = "world";
if (strcmp($str1, $str2) == 0) {
echo "The two strings are the same.";
} else {
echo "The two strings are different.";
}
```
tp5 如果需要查询两个字符串中有一个相同的值
在tp5中,您可以使用PHP中的字符串函数`strpos()`来判断一个字符串中是否包含另一个字符串。如果两个字符串中有一个相同的值,则可以使用以下代码进行判断:
```php
$str1 = "hello world";
$str2 = "world";
if(strpos($str1, $str2) !== false) {
echo "The two strings have a common value.";
} else {
echo "The two strings do not have a common value.";
}
```
这段代码中,我们首先定义了两个字符串 `$str1` 和 `$str2`,然后使用`strpos()`函数来判断 `$str1` 是否包含 `$str2`,如果包含则说明两个字符串有相同的值。需要注意的是,`strpos()`函数返回的是匹配到的第一个字符所在的位置,如果返回值不是false,则说明找到了相同的值,因此需要使用`!== false`来判断。