<?php
$a = '';
if($a exist 'some text')
echo 'text';
?>
Run Code Online (Sandbox Code Playgroud)
假设我有上面的代码,如何编写语句"if($ a exists'some text')"?
Dai*_*Dai 158
使用该strpos功能:http://php.net/manual/en/function.strpos.php
$haystack = "foo bar baz";
$needle = "bar";
if( strpos( $haystack, $needle ) !== false) {
echo "\"bar\" exists in the haystack variable";
}
Run Code Online (Sandbox Code Playgroud)
在你的情况下:
if( strpos( $a, 'some text' ) !== false ) echo 'text';
Run Code Online (Sandbox Code Playgroud)
请注意,我使用的!==运营商(而不是!= false或者== true甚至仅仅if( strpos( ... ) ) {)是因为"truthy" /"falsy"的PHP处理的返回值的性质strpos.
Ble*_*der 16
空字符串是假的,所以你可以写:
if ($a) {
echo 'text';
}
Run Code Online (Sandbox Code Playgroud)
虽然如果您询问该字符串中是否存在特定的子字符串,您可以使用它strpos()来执行此操作:
if (strpos($a, 'some text') !== false) {
echo 'text';
}
Run Code Online (Sandbox Code Playgroud)
http://php.net/manual/en/function.strpos.php 我认为如果字符串中存在“某些文本”,您会感到奇怪吗?
if(strpos( $a , 'some text' ) !== false)
Run Code Online (Sandbox Code Playgroud)