如何检查字符串如何在PHP中包含一个子字符串

本教程将帮助您检查字符串是否包含PHP编程语言中的任何子字符串。 例如,只有当任何输入字符串中包含其他子字符串时,才想运行特定的代码行。

示例1:

以下代码将评估为true,因为主字符串$ str中包含子字符串“ This ”。 这将打印“真”。

<?php $str = 'This is Main String'; if (strpos($str, 'This') !== false) { echo 'true'; } ?>
1
2
3
4
5
6
7
<?php
$str = 'This is Main String' ;
 
if ( strpos ( $str , 'This' ) !== false ) {
     echo 'true' ;
}
?>

Example 2:

The following code will evaluate to false because the main string $str doesn’t contains the substring ‘ Hello ‘ in it. This will nothing print.

<?php $str = 'This is Main String'; $substr = "Hello"; if (strpos($str, $substr) !== false) { echo 'true'; } ?>
1
2
3
4
5
6
7
8
<?php
$str = 'This is Main String' ;
$substr = "Hello" ;
 
if ( strpos ( $str , $substr ) !== false ) {
     echo 'true' ;
}
?>

Example 3: String Contains Substring on Start

The following code will check if a String conatins a substring at start. The following code will evaluate to true because the main string $str contains the substring ‘ This ‘ at start.

<?php $str = 'This is Main String'; if (strpos($str, 'This') == 0 ) { echo 'true'; } ?>
1
2
3
4
5
6
7
<?php
$str = 'This is Main String' ;
 
if ( strpos ( $str , 'This' ) == 0 ) {
     echo 'true' ;
}
?>

Share on Facebook Share
0
Share on Twitter Tweet
0
Share on Google Plus Share
0
Share on Pinterest Share
0
Share on Linkedin Share
0
Share on Digg Share
赞(52) 打赏
未经允许不得转载:优客志 » 系统运维
分享到:

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏