<?php
$a = '';
if($a exist 'some text')
echo 'text';
?>
假设我有上面的代码,如何编写语句“if($ a exists'some text')”?PHP - 如何检查一个字符串是否包含任何文本
<?php
$a = '';
if($a exist 'some text')
echo 'text';
?>
假设我有上面的代码,如何编写语句“if($ a exists'some text')”?PHP - 如何检查一个字符串是否包含任何文本
使用strpos
$haystack = "foo bar baz";
$needle = "bar";
if(strpos($haystack, $needle) !== false) {
echo "\"bar\" exists in the haystack variable";
}
你的情况:
if(strpos($a, 'some text') !== false) echo 'text';
请注意,我用的!==
运营商(而不是!= false
或== true
甚至只是if(strpos(...)) {
)是因为 “truthy”/“falsy的“PHP的处理strpos
的返回值的性质。
空字符串falsey,所以你可以这样写:
if ($a) {
echo 'text';
}
但如果你要问,如果在该字符串中存在一个特定的字符串,可以使用strpos()
做到这一点:
if (strpos($a, 'some text') !== false) {
echo 'text';
}
此外,如果你想要找到“一些文本”,“SOME TEXT”,等等。用'stripos'(这是不区分大小写) – Dave 2013-03-09 00:02:49
http://php.net/manual/en/function.strpos.php我认为你是wondiner,如果'一些文本'存在于字符串中吗?
if(strpos($a , 'some text') !== false)
可以使用==
comparison operator检查变量是否等于文本:
if($a == 'some text') {
...
您还可以使用strpos
函数返回一个字符串的第一次出现:
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
您可以使用strpos()
或stripos()
来检查字符串是否包含给定的针。它将返回找到的位置,否则将返回FALSE。
使用运算符===
或`!==在PHP中将0与FALSE相区别。
如果你需要知道的话,你可以使用这个字符串存在一个词,你可以使用此代码
$a = '';
if(!empty($a))
echo 'text';
。如果你只是想知道变量是否是一个字符串,从你的问题不明确。 “单词”是你在字符串中搜索的单词。
if (strpos($a,'word') !== false) {
echo 'true';
}
或使用is_string方法。哪些在给定变量上返回true或false。
<?php
$a = '';
is_string($a);
?>
确实要检查$ a是否为非空字符串? 这样它只包含任何文本? 然后下面的工作。
如果$ a包含字符串,可以使用以下命令:
if (!empty($a)) { // Means: if not empty
...
}
如果你还需要确认$一实际上是一个字符串,使用:
if (is_string($a) && !empty($a)) { // Means: if $a is a string and not empty
...
}
你的意思是这样的: 'if($ a =='some text')'。这里有一些关于运算符的更多信息:http://www.php.net/manual/en/language.operators.comparison.php – stUrb 2013-03-08 23:49:07
如果字符串的大小大于0,那么字符串中会包含一些文本。 – 2017-10-16 07:59:19
如果你正在检查的字符串,如果有任何文本,然后这应该工作'如果(strlen的($ A)> 0)回声“文本”;'或者如果您关注的是检查特定单词按照@Dai答案。 – 2017-10-16 08:01:11