PHP

Find a specific word in string in PHP

April 22, 2022

Find a specific word in string in PHP

In this article we will learn how to find a specific word in string – in an easy way, using a native method of the language

find a specific word in string thumb

What’s up programmer, how are you? Let’s learn more about PHP and string methods!

We have a few ways to check if a string contains a specific word, and not just a word, but any portion of text.

The first option we are going to use is the strpos method, which checks the position of a specific string in another string

If it is found, some value is returned, which is the initial position of the string in the longer string

And if not, a false is returned, see it in practice:

<?php
 $str = 'Testing the strpos function';

 if (strpos($str, 'function') !== false) {
  echo 'We have the word function in our string!';
 }

In this example the word test exists in the string, causing the if block to be executed

This is the way to check strings with strpos

Another variation is with preg_match, in this method we can insert a regular expression

See an example:

<?php

 $str = 'PHP is cool';
 $search = 'cool';

 if(preg_match("/{$search}/i", $str)) {
  echo 'The word cool is in our string!';
 }

So what is the difference between both of them?

Both alternatives meet our problem perfectly

But strpos finds any part of the string in a longer string, i.e. it’s not the specific word

If you search for test, and the string is iiiitesteiiii, it will find a result, because the word test is in the string, and that could be a problem

The preg_match will respect your regex, that is, you can have more accurate results

About performance: strpos method does better than preg_match, it runs 3 times faster

Conclusion

In this article we learned how to find a specific word in string

We use two approaches: strpos and preg_match

The first works in a broader way, being able to find strings even inside words

The preg_match respects the regex that was inserted as a parameter in the search in the middle of a string

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x