[php] How to check if a string contains a specific text

<?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')"?

This question is related to php

The answer is


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';
}

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.


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";
}

See documentation


Do mean to check if $a is a non-empty string? So that it contains just any text? Then the following will work.

If $a contains a string, you can use the following:

if (!empty($a)) {      // Means: if not empty
    ...
}

If you also need to confirm that $a is actually a string, use:

if (is_string($a) && !empty($a)) {      // Means: if $a is a string and not empty
    ...
}

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)

you can use this code

$a = '';

if(!empty($a))
  echo 'text';

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);
?>