search
HomeBackend DevelopmentPHP Tutorialphp strstr查找字符串中是否包含某些字符的查找函数_PHP

PHP 判断字符串是否包含其它字符

以下几个函数均可用来判断某字符串是否包含另外一个字符串PHP 中判断一个字符串是否包含其它字符是很常见的操作。 虽然很简单,但还是写了几个函数,质量可能不是很高,权当锻炼。 如果这几个函数恰好能帮上你的忙,我将会很高兴的。这几个函数中,我比较喜欢第四个。。。
复制代码 代码如下:
/**
* 以下几个函数均可用来判断某字符串是否包含另外一个字符串
* PHP 中判断一个字符串是否包含其它字符是很常见的操作。
* 虽然很简单,但还是写了几个函数,质量可能不是很高,权当锻炼。
* 如果这几个函数恰好能帮上你的忙,我将会很高兴的。
*/
/**
* 利用一下 strpos() 函数
* @param unknown_type $haystack
* @param unknown_type $needle
*/
function isInString1($haystack, $needle) {
//防止$needle 位于开始的位置
$haystack = '-_-!' . $haystack;
return (bool)strpos($haystack, $needle);
}
/**
* 利用字符串分割
* @param unknown_type $haystack
* @param unknown_type $needle
*/
function isInString2($haystack, $needle) {
$array = explode($needle, $haystack);
return count($array) > 1;
}
/**
* 用了一下正则,这种方法十分不建议,尤其是 $needle 中包含
* 特殊字符,如 ^,$,/ 等等
* @param unknown_type $haystack
* @param unknown_type $needle
*/
function isInString3($haystack, $needle) {
$pattern = '/' . $needle . '/';
return (bool)preg_match($pattern, $haystack);
}
/**
* 利用一下 strpos() 函数
* @param unknown_type $haystack
* @param unknown_type $needle
*/
function isInString4($haystack, $needle) {
return false !== strpos($haystack, $needle);
}
//测试
$haystack = 'I am ITBDW';
$needle = 'IT';
var_dump(isInString1($haystack, $needle));

我觉得最简单的就是这种了 strpos($a, $b) !== false 如果$a 中存在 $b,则为 true ,否则为 false。
用 !== false (或者 === false) 的原因是如果 $b 正好位于$a的开始部分,那么该函数会返回int(0),那么0是false,但$b确实位于$a中,所以要用 !== 判断一下类型,要确保是严格的 false。昨天晚上去中关村图书大厦,看到一本书中用的是 strpos === true 来判断,这是极其不正确的。。。
出错的书为《PHP求职宝典》107页(2012-02-26更新)
其它的还有 PHP 原生支持的函数,如 strstr(),stristr() 等,直接判断就可以了。

定义和用法
strstr() 函数搜索一个字符串在另一个字符串中的第一次出现。

该函数返回字符串的其余部分(从匹配点)。如果未找到所搜索的字符串,则返回 false。

语法
strstr(string,search)

参数 描述
string 必需。规定被搜索的字符串。
search 必需。规定所搜索的字符串。如果该参数是数字,则搜索匹配数字 ASCII 值的字符。

提示和注释
注释:该函数是二进制安全的。

注释:该函数对大小写敏感。如需进行大小写不敏感的搜索,请使用 stristr()。

例子 1
复制代码 代码如下:
echo strstr("Hello world!","world");
?>

//输出:world!

例子 2
在本例中,我们将搜索 "o" 的 ASCII 值所代表的字符:
复制代码 代码如下:
echo strstr("Hello world!",111);
?>

//输出:o world!

例子 3
复制代码 代码如下:
$email = 'admin@bitsCN.com';
$domain = strstr($email, '@');
echo $domain; // prints @bitsCN.com

$user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints admin
?>

复制代码 代码如下:
$city_str=fopen(cgi_path."/data/weather/city.dat","r");
$city_ch=fread($city_str,filesize(cgi_path."/data/weather/city.dat"));
$city_ch_arr=explode("|",$city_ch);
//如果能匹配到所在市
if(strstr($area_ga,"市")){
foreach($city_ch_arr as $city_ch_arr_item){
if(@strstr($area_ga,$city_ch_arr_item)){
echo $area_ga.'
';
echo $city_ch_arr_item;
$s_city=$city_ch_arr_item;
}
}
}
//如果找不到市 那么看看是不是能找到省 有时会有这样的情况:广东省长城宽带 这样的一律归属到该省省府
elseif(strstr($area_ga,"河北")!==false){
$s_city="石家庄";
}elseif(strstr($area_ga,"福建")!==false){
$s_city="福州";
}elseif(strstr($area_ga,"台湾")!==false){
$s_city="台北";
}elseif(strstr($area_ga,"香港")!==false){
$s_city="香港";
}elseif(strstr($area_ga,"广西")!==false){
$s_city="南宁";
}elseif(strstr($area_ga,"浙江")!==false){
$s_city="杭州";
}elseif(strstr($area_ga,"江苏")!==false){
$s_city="南京";
}elseif(strstr($area_ga,"山东")!==false){
$s_city="济南";
}elseif(strstr($area_ga,"安徽")!==false){
$s_city="合肥";
}elseif(strstr($area_ga,"湖南")!==false){
$s_city="长沙";
}elseif(strstr($area_ga,"四川")!==false){
$s_city="成都";
}elseif(strstr($area_ga,"云南")!==false){
$s_city="昆明";
}elseif(strstr($area_ga,"广东")!==false){
$s_city="广州";
}elseif(strstr($area_ga,"贵州")!==false){
$s_city="贵阳";
}elseif(strstr($area_ga,"西藏")!==false){
$s_city="拉萨";
}elseif(strstr($area_ga,"新疆")!==false){
$s_city="乌鲁木齐";
}elseif(strstr($area_ga,"蒙古")!==false){
$s_city="呼和浩特";
}elseif(strstr($area_ga,"黑龙江")!==false){
$s_city="哈尔滨";
}elseif(strstr($area_ga,"辽宁")!==false){
$s_city="沈阳";
}elseif(strstr($area_ga,"吉林")!==false){
$s_city="长春";
}elseif(strstr($area_ga,"河南")!==false){
$s_city="郑州";
}elseif(strstr($area_ga,"湖北")!==false){
$s_city="武汉";
}elseif(strstr($area_ga,"山西")!==false){
$s_city="太原";
}elseif(strstr($area_ga,"陕西")!==false){
$s_city="西安";
}elseif(strstr($area_ga,"甘肃")!==false){
$s_city="兰州";
}elseif(strstr($area_ga,"宁夏")!==false){
$s_city="银川";
}elseif(strstr($area_ga,"海南")!==false){
$s_city="海口";
}elseif(strstr($area_ga,"江西")!==false){
$s_city="南昌";
}elseif(strstr($area_ga,"澳门")!==false){
$s_city="澳门";
}
//如果都不存在 就是默认显示广州 比如本地机
else{
$s_city="广州";
}

如上代码:
其中 city.dat中是一些城市 格式是这样的
复制代码 代码如下:
广州|深圳|汕头|惠州|珠海|揭阳|佛山|河源|阳江|茂名|湛江|梅州|肇庆|韶关|潮州|东莞|中山|清远|江门|汕尾|云浮|增城|从化|乐昌|南雄|台山|开平|鹤山|恩平|廉江|雷州|吴川|高州|化州|高要|四会|兴宁|陆丰|阳春|英德|连州|普宁|罗定|北京|天津|上海|重庆|乌鲁木齐|克拉玛依|石河子|阿拉尔|图木舒克|五家渠|哈密|吐鲁番|阿克苏|喀什|和田|伊宁|塔城|阿勒泰|奎屯|博乐|昌吉|阜康|库尔勒|阿图什|乌苏|拉萨|日喀则|银川|石嘴山|吴忠|固原|中卫|呼和浩特|包头|乌海|赤峰|通辽|鄂尔多斯|呼伦贝尔|巴彦淖尔|乌兰察布|霍林郭勒|满洲里|牙克石|扎兰屯|根河|额尔古纳|丰镇|锡林浩特|二连浩特|乌兰浩特|

参考
复制代码 代码如下:
echo strstr('aaaaaaaaaaaboaaaaaaaaaaaaboxcccccccccbcccccccccccccc','box')."
\n";
//输出boxcccccccccbcccccccccccccc
// 完整匹配中间的box 不因前而的b而停止
echo strstr('aaaaaaAbaaa aaaa aaaaaaaaaboxccccccccccccboxccccccccccc','box')."
\n";
//输出boxccccccccccccboxccccccccccc
// 有两个关键字时, 遇到第一个停止.
echo strstr('Subscrtibe our to free newsletter about New Freew to','to')."
\n";
//输出to free newsletter about New Freew to
?>

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.