PHP 中有多种方法可以用来查找字符串。下面介绍一些常用的字符串查找函数及其用法。
1. strpos 函数:该函数用于在字符串中查找第一次出现的子字符串,并返回其位置。如果未找到子字符串,则返回 false。
使用方法:
```php
$string = "Hello, world!";
$position = strpos($string, "world");
if ($position !== false) {
echo "子字符串 'world' 在位置 " . $position . " 上找到了。";
} else {
echo "未找到子字符串 'world'。";
}
```
2. stripos 函数:与 strpos 类似,但它不区分大小写。
使用方法:
```php
$string = "Hello, world!";
$position = stripos($string, "WORLD");
if ($position !== false) {
echo "子字符串 'WORLD' 在位置 " . $position . " 上找到了。";
} else {
echo "未找到子字符串 'WORLD'。";
}
```
3. strrpos 函数:该函数用于在字符串中查找最后一次出现的子字符串,并返回其位置。如果未找到子字符串,则返回 false。
使用方法:
```php
$string = "Hello, world! Hello again!";
$position = strrpos($string, "Hello");
if ($position !== false) {
echo "最后一次出现 'Hello' 的位置是 " . $position . "。";
} else {
echo "未找到子字符串 'Hello'。";
}
```
4. strripos 函数:与 strrpos 类似,但它不区分大小写。
使用方法:
```php
$string = "Hello, world! Hello again!";
$position = strripos($string, "HELLO");
if ($position !== false) {
echo "最后一次出现 'HELLO' 的位置是 " . $position . "。";
} else {
echo "未找到子字符串 'HELLO'。";
}
```
5. strstr 函数:该函数用于在字符串中查找第一次出现的子字符串,并返回该子字符串及其后面的内容。如果未找到子字符串,则返回 false。
使用方法:
```php
$string = "This is a sentence.";
$substring = strstr($string, "is");
if ($substring !== false) {
echo "子字符串 'is' 在位置 " . $substring . " 的地方第一次出现。";
} else {
echo "未找到子字符串 'is'。";
}
```
6. stristr 函数:与 strstr 类似,但它不区分大小写。
使用方法:
```php
$string = "This is a sentence.";
$substring = stristr($string, "IS");
if ($substring !== false) {
echo "子字符串 'IS' 在位置 " . $substring . " 的地方第一次出现。";
} else {
echo "未找到子字符串 'IS'。";
}
```
以上是一些常见的字符串查找函数,可以根据具体的需求选择适合的函数来实现字符串查找功能。 如果你喜欢我们三七知识分享网站的文章, 欢迎您分享或收藏知识分享网站文章 欢迎您到我们的网站逛逛喔!https://www.ynyuzhu.com/
发表评论 取消回复