How to Check if a String Contains a Specific Word in PHP

In PHP, checking if a string contains a specific word is a common task when processing text data. Whether you’re building a search function, filtering content, or analyzing user input, knowing how to efficiently identify the presence of a word within a string is crucial.

This article will explore different methods to achieve this goal, ranging from simple string manipulation to more robust regular expressions.

1. Using strpos() Function

The strpos() function is a fundamental PHP function for finding the position of a substring within a string. If the substring is found, it returns the starting position of the first occurrence; otherwise, it returns false.

<?php

$string = "This is a sample string.";
$word = "sample";

if (strpos($string, $word) !== false) {
    echo "The string contains the word '$word'.";
} else {
    echo "The string does not contain the word '$word'.";
}

?> 

Important: Note that strpos() returns the position of the first occurrence of the substring. If you need to find all occurrences, you’ll need a different approach.

2. Using strstr() Function

The strstr() function searches for the first occurrence of a substring within a string and returns the portion of the string from the beginning up to and including the substring. If the substring is not found, it returns false.

<?php

$string = "This is a sample string.";
$word = "sample";

if (strstr($string, $word)) {
    echo "The string contains the word '$word'.";
} else {
    echo "The string does not contain the word '$word'.";
}

?>

3. Using Regular Expressions with preg_match()

For more complex scenarios, regular expressions provide a powerful and flexible solution. The preg_match() function checks if a pattern matches a subject string.

<?php

$string = "This is a sample string.";
$word = "sample";

if (preg_match("/\b$word\b/", $string)) {
    echo "The string contains the word '$word'.";
} else {
    echo "The string does not contain the word '$word'.";
}

?>

In this example, we used word boundaries (\b) to ensure that we only match the whole word and not substrings like “samples” or “sampling”.

Choosing the Right Method

  • strpos(): Ideal for simple cases where you only need to check for the presence of a specific substring within a string.
  • strstr(): Similar to strpos() but returns the portion of the string until the found substring, useful if you need that portion.
  • preg_match(): The most versatile option, especially when you need to apply advanced pattern matching or consider word boundaries.

By understanding these methods and their nuances, you can confidently implement word-checking functionality in your PHP applications, enhancing your ability to process and analyze text data effectively. Remember to choose the method that best suits your specific needs and complexity of the task.

PHP: How to Check if a String Contains a Specific Word – FAQs

Q: How can I check if a string contains a specific word in PHP?

A: You can use the strpos() function to check if a string contains a specific word. This function returns the position of the first occurrence of the word within the string. If the word is not found, it returns false.

$string = "This is a sample string.";
$word = "sample";

if (strpos($string, $word) !== false) {
  echo "The string contains the word '$word'.";
} else {
  echo "The string does not contain the word '$word'.";
}

Q: What if the word I’m searching for is part of a larger word?

A: If you want to ensure that you’re only matching the whole word and not just a substring, you can use regular expressions with preg_match().

$string = "This is a sample string.";
$word = "/\bsample\b/"; // Use word boundaries

if (preg_match($word, $string)) {
  echo "The string contains the word 'sample'.";
} else {
  echo "The string does not contain the word 'sample'.";
} 

Q: What are word boundaries and why are they important?

A: Word boundaries (\b in the regular expression) ensure that the match only occurs when the word is surrounded by spaces or other non-alphanumeric characters. This prevents matching words that are part of a larger word. For example, “sample” would be matched but “examples” would not.

Q: Can I check for case-insensitive matches?

A: Yes, you can use the stripos() function (for strpos()) or the i modifier in your regular expression (for preg_match()).

// Using stripos()
if (stripos($string, $word) !== false) {
  // ...
}

// Using preg_match() with the i modifier
if (preg_match("/\bsample\b/i", $string)) {
  // ...
}

Q: Is there a difference between strpos() and strstr()?

A: Yes, both check for the existence of a substring, but strpos() returns the position of the first occurrence, while strstr() returns the portion of the string starting from the first occurrence of the substring.

Q: Which method is more efficient?

A: strpos() is generally more efficient for simple word checks, while preg_match() with regular expressions is more powerful for complex matching scenarios. If you only need to check for the presence of a specific word, strpos() is usually a better choice.

I hope these FAQs are helpful in understanding how to check if a string contains a specific word in PHP. Feel free to ask further questions!

Related Article
50+ PHP Interview Questions and Answers 2023

1. Differentiate between static and dynamic websites. Static Website The content cannot be modified after the script is executed The Read more

All We Need to Know About PHP Ecommerce Development

  Many e-commerce sites let you search for products, show them off, and sell them online. The flood of money Read more

PHP Custom Web Development: How It Can Be Used, What Its Pros and Cons Are,

PHP is a scripting language that runs on the server. It uses server resources to process outputs. It is a Read more

PHP Tutorial

PHP Tutorial – Complete Guide for Beginners to Advanced Welcome to the most comprehensive PHP tutorial available online at PHPOnline.in Read more

Introduction of PHP

Introduction to PHP – Learn PHP from Scratch with Practical Examples Welcome to your complete beginner's guide to PHP. Whether Read more

Syntax Overview of PHP

Syntax Overview of PHP (2025 Edition) Welcome to phponline.in, your one-stop platform for mastering PHP. This comprehensive, SEO-rich tutorial on Read more

Environment Setup in PHP

Setting Up PHP Environment (Beginner’s Guide) If you’re planning to learn PHP or start developing websites using PHP, the first Read more

Variable Types in PHP

PHP Variable Types: Complete Beginner's Guide to PHP Data Types Welcome to phponline.in, your trusted source for beginner-to-advanced level PHP Read more

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments