Checking if a string contains another string with PHP
Published on 2022-04-15 • Modified on 2022-04-15
This snippet shows how to check if a string contains another string with PHP. This is a kind of tribute to our "old" PHP. The str_contains()
function was only introduced in PHP 8! Before, we had to do an ugly trick, as shown in the first example. Be careful that this new PHP 8 function is case sensitive. We can also use the Symfony String component, which allows choosing whether the search should be case sensitive. Once again, it is so elegant to use.
<?php
declare(strict_types=1);
namespace App\Controller\Snippet;
use function Symfony\Component\String\u;
/**
* I am using a PHP trait to isolate each snippet in a file.
* This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
* or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
* Services are injected in the main controller constructor.
*/
trait Snippet198Trait
{
/**
* @noinspection PhpStrFunctionsInspection
*/
public function snippet198(): void
{
$haystack = 'Foobar is a good friend of mine!';
$needle = 'friend';
// old way
if (strpos($haystack, $needle) !== false) {
echo "strpos: YES, $haystack contains $needle!".PHP_EOL;
}
// PHP 8
if (str_contains($haystack, $needle)) {
echo "str_contains: YES, $haystack contains $needle!".PHP_EOL;
}
// Symfony String component
if (u($haystack)->containsAny($needle)) {
echo "Symfony string: YES, $haystack contains $needle!".PHP_EOL.PHP_EOL;
}
// the case doesn't match now...
$needle = 'FrIenD';
if (strpos($haystack, $needle) !== false) {
echo "strpos: YES, $haystack contains $needle!";
} else {
echo "strpos: NO, $haystack does not contains $needle!".PHP_EOL;
}
if (str_contains($haystack, $needle)) {
echo "str_contains: YES, $haystack contains $needle!".PHP_EOL;
} else {
echo "str_contains: NO, $haystack does not contains $needle!".PHP_EOL;
}
// we can ignore case with the String component!
if (u($haystack)->ignoreCase()->containsAny($needle)) {
echo "Symfony string: YES, $haystack contains $needle! (ignoring case)".PHP_EOL.PHP_EOL;
}
// That's it! 😁
}
}
Run this snippet More on Stackoverflow Read the doc More on the web Random snippet
Call to action
Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )
- Report any error/typo.
- Report something that could be improved.
- Like and repost!
- Follow me on Bluesky 🦋
- Subscribe to the RSS feed.
- Click on the More on Stackoverflow buttons to make me win "Announcer" badges 🏅.
Thank you for reading! And see you soon on Strangebuzz! 😉
