How to check if a string contains a specific text [duplicate]
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";
}
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';
}
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 strpos()
or stripos()
to check if the string contain the given needle. It will return the position where it was found, otherwise will return FALSE.
Use the operators ===
or `!== to differ FALSE from 0 in PHP.