本教程将帮助您检查字符串是否包含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'
;
}
?>
|