Check for text in a line

Since PHP 8.0, the str_contains() function has become available.

str_contains('PHP-script', 'PHP'); // true
str_contains('PHP-script', 'Python'); // false

Prior to PHP 8.0, the strpos() function was used, which returns the position of the specified text. If the text is not found, the function returns -1.

$text = 'PHP-script';
if (strpos($text, 'PHP') !== false) {
    echo 'string found';
}

You can also specify a third parameter that specifies where to start searching for the string.

Beginning and end of line

Since PHP 8.0, it has been possible to check that a given string starts or ends with a given string:

// The line starts with "PHP"
str_starts_with('PHP-script', 'PHP'); // true
str_starts_with('Script PHP', 'PHP'); // false

// The line ends with "PHP"
str_ends_with('PHP-script', 'PHP'); // false
str_ends_with('Script PHP', 'PHP'); // PHP

Regular expression

You can check for the presence of text using regular expressions using the preg_match() function.

$text = 'PHP-script';
if (preg_match('/PHP/', $text)) {
    echo 'string found';
}

If you just need to find text, as in the example above, then for performance reasons it is better to use the strpos() function. This is also written in the official documentation php.net/manual/en/function.preg-match.php.

For more complex text searches, you can use preg_match().

// The code checks for the presence of the strings "PHP-script" and "Python-script"
$text = 'PHP-script';
if (preg_match('/(PHP|Python)-script/', $text)) {
    echo 'string found';
}