PHP中查询字符串通常包含在URL中,用于传递参数。它以问号(?)开始,后跟一系列键值对,每对之间用&符号分隔。
example.php?name=John&age=25。可以使用$_GET全局变量来获取这些值。在PHP中,我们可以使用strpos()函数来检查一个字符串是否包含另一个字符串,这个函数返回的是子字符串在主字符串中第一次出现的位置,如果没有找到则返回false。

(图片来源网络,侵权删除)
使用方法
$haystack = 'Hello, world!';
$needle = 'world';
if (strpos($haystack, $needle) !== false) {
echo "'$needle' found in '$haystack'";
} else {
echo "'$needle' not found in '$haystack'";
}
示例代码
<?php
function check_string_contains($main_string, $sub_string) {
return strpos($main_string, $sub_string) !== false;
}
$main_string = "This is a sample string.";
$sub_string = "sample";
if (check_string_contains($main_string, $sub_string)) {
echo "The main string contains the substring.";
} else {
echo "The main string does not contain the substring.";
}
?>
注意事项
1、strpos()函数是区分大小写的,所以如果你需要不区分大小写的搜索,可以使用stripos()函数。
2、如果需要检查多个子字符串是否存在于主字符串中,可以多次调用strpos()或stripos()函数。
3、如果要检查的子字符串为空字符串,strpos()会返回0,而stripos()也会返回0,在使用这些函数时,应确保子字符串不为空。

(图片来源网络,侵权删除)
相关问题与解答
问题1:如何在PHP中检查一个字符串是否以另一个字符串开头?
答案:你可以使用strncmp()函数或者startsWith()方法(PHP 8.0及以上版本)来检查一个字符串是否以另一个字符串开头。
$string = "Hello, world!";
$prefix = "Hello";
if (strncmp($string, $prefix, strlen($prefix)) == 0) {
echo "The string starts with the prefix.";
} else {
echo "The string does not start with the prefix.";
}
或者使用PHP 8.0及以上版本的startsWith()方法:
$string = "Hello, world!";
$prefix = "Hello";
if ($string>startsWith($prefix)) {
echo "The string starts with the prefix.";
} else {
echo "The string does not start with the prefix.";
}
问题2:如何在PHP中替换字符串中的某个子串?
答案:你可以使用str_replace()函数来替换字符串中的某个子串。

(图片来源网络,侵权删除)
$search = 'world'; $replace = 'everyone'; $subject = 'Hello, world!'; $result = str_replace($search, $replace, $subject); echo $result; // 输出: Hello, everyone!
来源互联网整合,作者:小编,如若转载,请注明出处:https://www.aiboce.com/ask/20811.html