温馨提示×

PHP查找字符串的方法有哪几种

PHP
小亿
84
2024-04-22 09:54:43
栏目: 编程语言

在PHP中,查找字符串的方法有以下几种:

  1. strpos()函数:用于在字符串中查找一个子字符串,并返回子字符串第一次出现的位置。如果未找到子字符串,则返回false。
$string = 'Hello, World!';
$substring = 'World';
$position = strpos($string, $substring);
echo $position;
  1. strrpos()函数:用于在字符串中查找一个子字符串,并返回子字符串最后一次出现的位置。如果未找到子字符串,则返回false。
$string = 'Hello, World!';
$substring = 'o';
$position = strrpos($string, $substring);
echo $position;
  1. strstr()函数:用于在字符串中查找一个子字符串,并返回子字符串及其后面的所有内容。
$string = 'Hello, World!';
$substring = 'World';
$result = strstr($string, $substring);
echo $result;
  1. stristr()函数:用于在字符串中查找一个子字符串(不区分大小写),并返回子字符串及其后面的所有内容。
$string = 'Hello, World!';
$substring = 'world';
$result = stristr($string, $substring);
echo $result;
  1. substr()函数:用于从字符串中取出一部分内容,可以指定起始位置和长度。
$string = 'Hello, World!';
$substring = substr($string, 7, 5);
echo $substring;

0