How to check if a string contains a specific 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)
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';
}
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";
}