Jump to content
  • Hello visitors, welcome to the Hacker World Forum!

    Red Team 1949  (formerly CHT Attack and Defense Team) In this rapidly changing Internet era, we maintain our original intention and create the best community to jointly exchange network technologies. You can obtain hacker attack and defense skills and knowledge in the forum, or you can join our Telegram communication group to discuss and communicate in real time. All kinds of advertisements are prohibited in the forum. Please register as a registered user to check our usage and privacy policy. Thank you for your cooperation.

    TheHackerWorld Official

PHP检测一个字符串中是否包含另外一个字符或字符串

 Share


HACK1949

Recommended Posts

编写程序的时候,经常要处理字符串,最基本就是字符串的查找,您可能需要检查字符串是否包含特定的字符或子字符串,因为您可能必须对该子字符串或字符执行某些操作。我们将使用下面的3个php内置函数来检查一个字符串是否包含特定字符。

  1. PHP strrpos()函数
  2. PHP strstr()函数
  3. PHP preg_match()函数

 

PHP strrpos()函数

strrpos() 函数查找字符串在另一字符串中最后一次出现的位置。根据strrpos() 函数的特征,我们可以使用它来判断一个字符串中是否包含指定字符串。

首先来看一下strrpos()函数的语法和参数。

语法:

strrpos(string,find,start)

参数详细描述:

参数描述
string 必需。规定被搜索的字符串。
find 必需。规定要查找的字符。
start 可选。规定在何处开始搜索。

注意:字符串位置从 0 开始,不是从 1 开始。

例子:

<?php
	//从提交的表单中获取邮件信息并保存到变量$email中
	$email = $_POST['email'];

	//Inside if, we check using strpos function
	if (strpos($email, '@') !== false) {
		print 'There was @ in the e-mail address!';
	} else {
		print 'There was NO @ in the e-mail address!';
	}
?>

如何需要查找的字符对大小写不敏感,你可以使用strripos()。

 

PHP strstr()函数

strstr() 函数搜索一个字符串在另一个字符串中的第一次出现。该函数返回字符串的其余部分(从匹配点)。如果未找到所搜索的字符串,则返回 false。

语法

strstr(string,search,before_search)

参数描述: 

参数描述
string 必需。规定被搜索的字符串。
search

必需。规定所搜索的字符串。

如果此参数是数字,则搜索匹配此数字对应的 ASCII 值的字符。

before_search

可选。默认值为 "false" 的布尔值。

如果设置为 "true",它将返回 search 参数第一次出现之前的字符串部分。

例子: 

if (false !== strstr($source_str, $substring)) {
  echo 'Found!';
} else {
  echo 'Not found!';
}

 

PHP preg_match()函数

另一种方法是使用正则表达式结合PHP preg_match 函数检查一个字符串是否包含另一个字符 。如果匹配,此函数将返回true,否则返回false。preg_match语法语法如下:

preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

以下是一个非常简单的匹配:

if (preg_match("/neeDle/i", "There's a small needle in a haystack")) {
    echo "Found!";
} else {
    echo "Not found!";
}

正则表达式最后的字符“i”表示匹配不区分大小写。

以上就是本文的全部内容,希望对大家的学习有所帮助。更多教程请访问码农之家
Link to post
Link to comment
Share on other sites

 Share

discussion group

discussion group

    You don't have permission to chat.
    • Recently Browsing   0 members

      • No registered users viewing this page.
    ×
    ×
    • Create New...