1.2.307. Could Use strcontains()

PHP 8 introduced the strcontains() function, which is a replacement for strpos(). strcontains() checks if a string is found inside a string, and returns a boolean.

When strpos() is used as a boolean, or compared to a boolean, strcontains() is a good replacement. When strpos() is actually used to calculate a position inside a string, it should not be replaced.

strcontains() is not backward compatible, so it should be be used before PHP 8.0. Polyfills are available.

<?php

// Could use strcontains()
if (strpos($haystack, $needle) !== false) { }

// Not a possible replacement
$position = strpos($haystack, $needle);
$haystack[$position + 1] = 'A';

?>

1.2.307.1. Suggestions

  • Replace strpos() by strcontains()

1.2.307.2. Specs

Short name

Structures/CouldUseStrContains

Rulesets

All, Changed Behavior, Rector, Suggestions

Exakat since

2.6.4

PHP Version

With PHP 8.0 and more recent

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

High

Available in

Entreprise Edition, Exakat Cloud