<?php
$a = '';
if($a exist 'some text')
echo 'text';
?>
Suppose I have the code above, how to write the statement if($a exist 'some text')?
Use the strpos function: 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";
}
In your case:
if( strpos( $a, 'some text' ) !== false ) echo 'text';
Note that my use of the !== operator (instead of != false or == true or even just if( strpos( ... ) ) {) is because of the "truthy"/"falsy" nature of PHP's handling of the return value of strpos.
As of PHP 8.0.0 you can now use str_contains
<?php
if (str_contains('abc', '')) {
echo "Checking the existence of the empty string will always
return true";
}
false >= 0. You have to write !== false, as 0 == false.String.IndexOf which returns -1 in event of a non-match. I've corrected my answer.stripos() for insensitive string comparison ...! operator will affect the falsiness of the return value from strpos which means === won't work the way it's intended.Empty strings are falsey, so you can just write:
if ($a) {
echo 'text';
}
Although if you're asking if a particular substring exists in that string, you can use strpos() to do that:
if (strpos($a, 'some text') !== false) {
echo 'text';
}
stripos (which is case insensitive)http://php.net/manual/en/function.strpos.php I think you are wondiner if 'some text' exists in the string right?
if(strpos( $a , 'some text' ) !== false)
If you need to know if a word exists in a string you can use this. As it is not clear from your question if you just want to know if the variable is a string or not. Where 'word' is the word you are searching in the string.
if (strpos($a,'word') !== false) {
echo 'true';
}
or use the is_string method. Whichs returns true or false on the given variable.
<?php
$a = '';
is_string($a);
?>
You can use the == comparison operator to check if the variable is equal to the text:
if( $a == 'some text') {
...
You can also use strpos function to return the first occurrence of a string:
<?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";
}
if($a == 'some text'). Here some more info over operators: php.net/manual/en/language.operators.comparison.phpif(strlen($a) > 0) echo 'text';or if your concern is to check for specific word the follow the @Dai answer.