strchr()函数在PHP内置函数,用于搜索给定的字符串(比如第一次出现的字符串searchstr)在另一个字符串(比如originalStr),并从返回字符串的其余部分originalStr从第一个开始在orignalStr中出现searchStr。
注意: strchr()函数区分大小写。
句法:
1 | strchr($originalStr,$searchStr,$before_search) |
参数:
- $ originalStr:此参数指定要在其中搜索单词的字符串。这是强制性的
- $ searchStr:它指定要在给定$ originalStr中搜索的单词,它也可以是字符或数字,如果传递了数字,它会在$ originalStr中搜索等效的ASCII值字符。这是强制性的。
- $ before_search:这是一个可选参数,当设置为True时,在第一次出现$ searchStr之前返回$ originalStr的一部分。默认设置为false。
返回值:根据以下三种情况返回一个字符串:
- 当找到$ searchStr时,它返回从$ originalStr中$ searchStr的第一次出现开始到$ originalStr的末尾的字符串。
- 当$ searchStr在给定的$ originalStr中不存在时,它不返回任何内容。
- 当$ before_search设置为TRUE 时,它会在$ searchStr第一次出现之前返回字符串的一部分。
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Input : $originalStr = "sky8g for sky8g" $searchStr = "sky8g" Output : sky8g for sky8g Input : $originalStr = "sky8g for sky8g" $searchStr = "for" Output : for sky8g Input : $originalStr = "striver has published 180 articles" $searchStr = "has" $before_search = TRUE Output : striver Input: $originalStr = "sky8g for sky8g" $searchStr = "gfg" Output: No output |
下面的程序说明了PHP中的strchr()函数:
1 2 3 4 5 6 7 8 9 10 11 | <?php // Program to demonstrate the chr() // function when word is found $originalStr = "sky8g for sky8g"; $searchStr = "sky8g" ; // prints the string from the // first occurence of the $searchStr echo strchr($originalStr, $searchStr); ?> |
输出
1 | sky8g for sky8g |
程序2:在找不到单词时演示strchr()函数的程序。
1 2 3 4 5 6 7 8 9 10 11 | <?php // Program to demonstrate the chr() // function when word is not found $originalStr = "sky8g for sky8g"; $searchStr = "gfg" ; // prints the string from the // first occurence of the $searchStr echo strchr($originalStr, $searchStr); ?> |
输出
1 | No Output |
程序3:当找到word并且$ before_search设置为true时,演示strchr()函数的程序。
1 2 3 4 5 6 7 8 9 10 11 12 | <?php // Program to demonstrate the chr() // function when word is found and // $before_search is set to true $originalStr = "sky8g for sky8g"; $searchStr = "for" ; // prints the string from the // first occurence of the word echo strchr($originalStr, $searchStr, true); ?> |
输出
1 | sky8g |
程序4:在传递和找到一部分单词时演示strchr()函数的程序。
1 2 3 4 5 6 7 8 9 10 11 | <?php // Program to demonstrate the chr() // function when a part of word is passed and found $originalStr = "sky8g for sky8g"; $searchStr = "eks" ; // prints the string from the // first occurence of the word echo strchr($originalStr, $searchStr); ?> |
输出
1 | eks for sky8g |
程序5:在传递数字并搜索其等效ASCII字符时演示strchr()函数的程序。
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php // Program to demonstrate the chr() // function when a number is passed and its equivalent // ASCII character is searched $originalStr = "sky8g for sky8g"; // 101 is the ASCII value of e $searchStr = 101 ; echo strchr($originalStr, $searchStr); ?> |
参考:http:
//php.net/manual/en/function.strchr.php