What is the purpose of `str_contains()` in PHP 8.4?
PHP

What is the purpose of `str_contains()` in PHP 8.4?

Symfony Certification Exam

Expert Author

January 29, 20266 min read
PHPSymfonystr_containsPHP DevelopmentWeb DevelopmentSymfony Certification

What is the Purpose of str_contains() in PHP 8.4?

As PHP evolves, its features become more refined and tailored for modern development practices. One of the standout additions in PHP 8.4 is the str_contains() function. This function streamlines string operations and enhances code readability, particularly in frameworks like Symfony, which heavily rely on string manipulation for various tasks. Understanding the purpose and applications of str_contains() is vital for developers preparing for the Symfony certification exam.

In this article, we will explore the purpose of str_contains(), its syntax, benefits, and practical examples within the context of Symfony applications.

What is str_contains()?

Introduced in PHP 8.0, the str_contains() function checks if a given substring exists within a string. It returns a boolean value: true if the substring is found and false otherwise.

Syntax

The syntax of str_contains() is straightforward:

bool str_contains(string $haystack, string $needle);
  • $haystack: The string to search within.
  • $needle: The substring to search for.

Example Usage

Here’s a basic example of how str_contains() can be utilized:

$string = "Hello, Symfony!";
$contains = str_contains($string, "Symfony");

if ($contains) {
    echo "The string contains 'Symfony'.";
} else {
    echo "The string does not contain 'Symfony'.";
}

In this example, the output would be "The string contains 'Symfony'." This simple function simplifies the way we check for substrings compared to older methods.

Why is str_contains() Important for Symfony Developers?

For Symfony developers, the str_contains() function provides a clean and efficient way to handle string checks in various scenarios. Here are some key reasons why it is important:

1. Improved Readability

Using str_contains() enhances code readability. Instead of using complex regex or strpos() checks, developers can express their intent clearly. For example:

if (str_contains($email, '@example.com')) {
    // Process email
}

This is much more understandable compared to:

if (strpos($email, '@example.com') !== false) {
    // Process email
}

2. Simplified Logic in Services

When building services in Symfony, developers often need to check for specific substrings in various contexts, such as validating user input, processing commands, or filtering data. The str_contains() function simplifies these operations, leading to cleaner code.

Example in a Symfony Service

Consider a service that validates user email domains:

namespace App\Service;

class EmailValidator
{
    public function isValidEmail(string $email): bool
    {
        return str_contains($email, '@example.com');
    }
}

In this example, the isValidEmail function directly communicates its purpose, making it easy for other developers to understand and maintain.

3. Integration with Twig Templates

In Symfony applications, Twig templates are extensively used for rendering views. The str_contains() function can be utilized within Twig to check for substrings, enhancing template logic.

Example in a Twig Template

{% if str_contains(user.email, '@example.com') %}
    <p>User has an example.com email.</p>
{% endif %}

This example demonstrates how str_contains() can be seamlessly integrated within Twig templates, allowing for expressive and readable conditions.

4. Usage in Doctrine DQL Queries

When working with Doctrine, developers often need to filter data based on string conditions. While Doctrine's DQL does not support str_contains() directly, similar logic can be implemented with the LIKE operator. However, understanding str_contains() helps when writing raw SQL queries or filtering collections.

Example in a Repository

public function findUsersByEmailDomain(string $domain): array
{
    return $this->createQueryBuilder('u')
        ->where('u.email LIKE :domain')
        ->setParameter('domain', '%' . $domain)
        ->getQuery()
        ->getResult();
}

While this does not use str_contains(), understanding its logic can help developers craft more efficient queries and conditions.

Advantages of Using str_contains()

1. Performance

The str_contains() function is optimized for performance, allowing for faster substring checks compared to older methods. This is particularly beneficial in applications where string operations are frequent and performance-sensitive.

2. Avoiding Common Pitfalls

Using strpos() can lead to common pitfalls, such as misinterpreting the return value. For example, strpos() returns 0 if the substring is found at the beginning of the string, which can be mistakenly interpreted as false. With str_contains(), this ambiguity is eliminated.

3. Cleaner Code

By using str_contains(), developers can write cleaner and more concise code, reducing the need for complex conditional statements or error-prone comparisons.

Practical Examples in Symfony Context

Let’s look at a few practical examples to illustrate how str_contains() can be used effectively in Symfony applications.

1. User Input Validation in Controllers

In a Symfony controller, you might want to validate user input before processing it. Using str_contains() can help ensure that the input meets specific criteria.

namespace App\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class UserController
{
    #[Route('/register', name: 'user_register')]
    public function register(Request $request): Response
    {
        $email = $request->request->get('email');

        if (!str_contains($email, '@example.com')) {
            return new Response('Invalid email domain.', Response::HTTP_BAD_REQUEST);
        }

        // Proceed with registration
        return new Response('Registration successful!');
    }
}

In this example, the controller checks if the provided email contains a specific domain before proceeding with the registration process.

2. Custom Validation Constraints

Developers can create custom validation constraints in Symfony that utilize str_contains(). This can be particularly useful for ensuring specific formats or substrings in user inputs.

Example of a Custom Validator

namespace App\Validator;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class ContainsSubstringValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        if (null === $value || '' === $value) {
            return;
        }

        if (!str_contains($value, $constraint->substring)) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ substring }}', $constraint->substring)
                ->addViolation();
        }
    }
}

3. Filtering Data in Services

In a service that processes user data, you might need to filter users based on their email addresses. Using str_contains() can streamline this operation.

namespace App\Service;

use App\Repository\UserRepository;

class UserService
{
    public function __construct(private UserRepository $userRepository) {}

    public function filterUsersByDomain(string $domain): array
    {
        $allUsers = $this->userRepository->findAll();
        return array_filter($allUsers, fn($user) => str_contains($user->getEmail(), $domain));
    }
}

In this service, the filterUsersByDomain method efficiently filters users based on the provided domain using str_contains().

4. Twig Filter Integration

You can also create custom Twig filters that utilize str_contains() to enhance template functionality.

Example of a Custom Twig Filter

namespace App\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class AppExtension extends AbstractExtension
{
    public function getFilters(): array
    {
        return [
            new TwigFilter('contains', [$this, 'contains']),
        ];
    }

    public function contains(string $haystack, string $needle): bool
    {
        return str_contains($haystack, $needle);
    }
}

You can then use this filter in your Twig templates:

{% if user.email|contains('@example.com') %}
    <p>User has an example.com email.</p>
{% endif %}

Conclusion

The str_contains() function introduced in PHP 8.4 is a powerful tool for Symfony developers, enabling cleaner, more readable, and efficient string operations. Its ability to check for the presence of substrings simplifies code and reduces common pitfalls associated with older methods.

For those preparing for the Symfony certification exam, mastering str_contains() and its applications is crucial. By understanding how to effectively utilize this function in controllers, services, and templates, you can enhance the quality of your Symfony applications and demonstrate your proficiency in modern PHP practices.

As you continue your learning journey, practice implementing str_contains() in various scenarios within your Symfony projects. This hands-on experience will solidify your understanding and prepare you for both the certification exam and real-world development challenges. Embrace this new feature, and leverage it to write cleaner, more maintainable code in your Symfony applications.