1.2.1358. Use str_contains()

str_contains() checks if a string is within another one. It replaces a call to strpos() with a comparison.

Note that this function is case sensitive : it cannot replace stripos().

Note that this function is single-byte only : it cannot replace mb_strpos().

This analysis omits calls to strpos() that are saved to a variable. strpos() is actually returning the position of the found string in the haystack, which may be reused later.

<?php

if (str_contains("abc", "a")) { doSomething(); }

// strpos is used only for detection.
if (strpos("abc", "a") !== false) { doSomething(); }

// strpos returns a position,
$pos = strpos("abca", "a", 3);
if ($pos > 3) { doSomething();

?>

See also PHP RFC: str_contains.

1.2.1358.1. Suggestions

  • Switch to str_contains()

1.2.1358.2. Specs

Short name

Php/UseStrContains

Rulesets

All, Suggestions

Exakat since

2.2.0

PHP Version

With PHP 8.0 and more recent

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

High

Features

string

Available in

Entreprise Edition, Exakat Cloud