<?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')"?
The includes() method returns true if a string contains a specified string. Otherwise it returns false .
You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false . Also note that string positions start at 0, and not 1.
string repeatedWord = "woooooooow"; for (int i = 0; i < repeatedWord. Count(); i++) { if (repeatedWord[i] == repeatedWord[i+1]) { // .... } } The code works but it will always have an error because the last character [i + 1] is empty/null.
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'; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With