I think you could probably just remove all the whitespace characters you care about (e.g., what about hyphenations?) and test for " word ":

var_dump(firstWordPosition('Will company any do any job, (are there any)?', 'any'));
var_dump(firstWordPosition('Will *any* company do *any* job, (are there any)?', 'any'));

function firstWordPosition($str, $word) {
    // There are others, maybe also pass this in or array_merge() for more control.
    $nonchars = ["'",'"','.',',','!','?','(',')','^','$','#','\n','\r\n','\t',];
    // You could also do a strpos() with an if and another argument passed in.
    // Note that we're padding the $str to with spaces to match begin/end.
    $pos = stripos(str_replace($nonchars, ' ', " $str "), " $word ");

    // Have to account for the for-space on " $str ".
    return $pos ? $pos - 1: false;
}

Gives 12 (offset from 0)

https://3v4l.org/qh9Rb

Answer from Jared Farrish on Stack Overflow
๐ŸŒ
PHP
php.net โ€บ manual โ€บ en โ€บ function.strpos.php
PHP: strpos - Manual
Passing an empty string as needle matches at every position. strpos() returns offset when it is specified, or 0 otherwise. Prior to PHP 8.0.0, if needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
๐ŸŒ
W3Schools
w3schools.com โ€บ php โ€บ โ€บ func_string_strpos.asp
PHP strpos() Function
Find the position of the first occurrence of "php" inside the string.
๐ŸŒ
Codecademy
codecademy.com โ€บ docs โ€บ php โ€บ string functions โ€บ strpos()
PHP | String Functions | strpos() | Codecademy
July 20, 2023 - The strpos() function performs a case-sensitive search for the position of the first occurrence of a substring in a given string. If the substring is found, it will return the index of the beginning of the substring.
Top answer
1 of 3
1

I think you could probably just remove all the whitespace characters you care about (e.g., what about hyphenations?) and test for " word ":

var_dump(firstWordPosition('Will company any do any job, (are there any)?', 'any'));
var_dump(firstWordPosition('Will *any* company do *any* job, (are there any)?', 'any'));

function firstWordPosition($str, $word) {
    // There are others, maybe also pass this in or array_merge() for more control.
    $nonchars = ["'",'"','.',',','!','?','(',')','^','$','#','\n','\r\n','\t',];
    // You could also do a strpos() with an if and another argument passed in.
    // Note that we're padding the $str to with spaces to match begin/end.
    $pos = stripos(str_replace($nonchars, ' ', " $str "), " $word ");

    // Have to account for the for-space on " $str ".
    return $pos ? $pos - 1: false;
}

Gives 12 (offset from 0)

https://3v4l.org/qh9Rb

2 of 3
0
<?php
$subject = "any";
$b = " ";
$delimited = "$b$subject$b";

$replace = array("?","*","(",")",",",".");
$str = "Will *any* company do *any* job, (are there any)?";
echo "\nThe string: \"$str\"";

$temp = str_replace($replace,$b,$str);
while ( ($pos = strpos($temp,$delimited)) !== false )
{
    echo "\nThe subject \"$subject\" occurs at position ",($pos + 1);
    for ($i=0,$max=$pos + 1 + strlen($subject); $i <= $max; $i++) {
        $temp[$i] = $b;
    }
}

See demo

The script defines a word boundary as a blank space. If the string has non-alphabetical characters, they are replaced with blank space and the result is stored in $temp. As the loop iterates and detects $subject, each of its characters changes into a space in order to locate the next appearance of the subject. Considering the amount of work involved one may wonder if such effort really pays off compared to using a regex with a preg_ function. That is something that one will have to decide themselves. My purpose was to show how this may be achieved using strpos() without resorting to the oft repeated conventional wisdom of SO which advocates using a regex.

There is an option if you are loathe to create a replacement array of non-alphabetical characters, as follows:

<?php

function getAllWholeWordPos($s,$word){
  $b = " ";
  $delimited = "$b$word$b";
  $retval = false;

  for ($i=0, $max = strlen( $s ); $i < $max; $i++) {
          if ( !ctype_alpha( $s[$i] ) ){
              $s[$i] = $b;
          }
  }

 while ( ( $pos = stripos( $s, $delimited) ) !== false ) {
    $retval[] = $pos + 1;
    for ( $i=0, $max = $pos + 1 + strlen( $word ); $i <= $max; $i++) {
        $s[$i] = $b;
    }
 }
 return $retval;
}

$whole_word = "any";    
$str = "Will *$whole_word* company do *$whole_word* job, (are there $whole_word)?";

echo "\nString: \"$str\""; 

$result = getAllWholeWordPos( $str, $whole_word );
$times = count( $result );
echo "\n\nThe word \"$whole_word\" occurs $times times:\n";
foreach ($result as $pos) { 
   echo "\nPosition: ",$pos;
}

See demo

Note, this example with its update improves the code by providing a function which uses a variant of strpos(), namely stripos() which has the added benefit of being case insensitive. Despite the more labor-intensive coding, the performance is speedy; see performance.

๐ŸŒ
Medium
medium.com โ€บ @jorisvdaalsvoort โ€บ the-hidden-pitfalls-why-empty-strpos-and-more-are-often-misunderstood-43800c88be33
PHP Pitfalls: Avoid empty(), strpos(), & More | Medium
February 24, 2025 - PHP, for all its power and flexibility, has its quirks. And some of the most commonly used functions harbor behaviors that are unintuitive, leading to subtle yet frustrating bugs. empty() might flag a perfectly valid value as "empty," strpos() can return 0 in ways that break conditionals, and in_array() may lead to loose comparisons that bite back.
๐ŸŒ
O'Reilly
oreilly.com โ€บ library โ€บ view โ€บ php-in-a โ€บ 0596100671 โ€บ re95.html
strpos() - PHP in a Nutshell [Book]
October 13, 2005 - The strpos() function, and its case-insensitive sibling, stripos(), returns the index of the beginning of a substring's first occurrence within a string.
Author: Paul Hudson
Published: 2005
Pages: 372
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ php โ€บ php-strpos-stripos-functions
PHP strpos() and stripos() Functions - GeeksforGeeks
May 9, 2022 - This returns an integer value of the position of the first occurrence of the string. This function is case-insensitive, which means it treats both upper-case and lower-case characters equally.
Find elsewhere
๐ŸŒ
Code.mu
code.mu โ€บ en โ€บ php โ€บ manual โ€บ string โ€บ strpos
The strpos Function - The Position of the First Occurrence of a Substring in PHP
The strpos function returns the position of the first occurrence of a substring in another string or false if the substring is not found.
๐ŸŒ
Hashnode
justdevthings.hashnode.dev โ€บ how-does-strpos-work-in-php
How Does strpos() Work In PHP?
May 12, 2023 - strpos() is a built-in function in PHP that is used to find the position of the first occurrence of a substring within a string.
Top answer
1 of 4
37

According to the PHP manual, yes- strpos() is the quickest way to determine if one string contains another.

Note:

If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead.

This is quoted time and again in any php.net article about other string comparators (I pulled this one from strstr())

Although there are two changes that should be made to your statement.

if (strpos($storage->getMessage($i),'chocolate') !== FALSE)

This is because if(0) evaluates to false (and therefore doesn't run), however strpos() can return 0 if the needle is at the very beginning (position 0) of the haystack. Also, removing htmlentities() will make your code run a lot faster. All that htmlentities() does is replace certain characters with their appropriate HTML equivalent. For instance, it replaces every & with &amp;

As you can imagine, checking every character in a string individually and replacing many of them takes extra memory and processor power. Not only that, but it's unnecessary if you plan on just doing a text comparison. For instance, compare the following statements:

strpos('Billy & Sally', '&'); // 6
strpos('Billy &amp; Sally', '&'); // 6
strpos('Billy & Sally', 'S'); // 8
strpos('Billy &amp; Sally', 'S') // 12

Or, in the worst case, you may even cause something true to evaluate to false.

strpos('<img src...', '<'); // 0
strpos('&lt;img src...','<'); // FALSE

In order to circumvent this you'd end up using even more HTML entities.

strpos('&lt;img src...', '&lt;'); // 0

But this, as you can imagine, is not only annoying to code but gets redundant. You're better off excluding HTML entities entirely. Usually HTML entities is only used when you're outputting text. Not comparing.

2 of 4
2

strpos is likely to be faster than preg_match and the alternatives in this case, the best idea would be to do some benchmarks of your own with real example data and see what is best for your needs, although that may be overdoing it. Don't worry too much about performance until it starts to become a problem

๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ php โ€บ php_function_strpos.htm
PHP String strpos() Function
The strpos() function returns the position of the first occurrence of a string within another string, or FALSE if no string is found. String positions begin at 0, not 1. First introduced in core PHP 4, the strpos() function continues to function ...
๐ŸŒ
Functions-Online
functions-online.com โ€บ strpos.html
test strpos online - PHP string functions - functions-online
Test and run strpos online in your browser. Returns the numeric position of the first occurrence of $needle in the $haystack string. Unlike the
๐ŸŒ
The Knowledge Academy
theknowledgeacademy.com โ€บ blog โ€บ php-strpos
PHP strpos() Function: Introduction, Syntax, Uses, & More
July 8, 2026 - The PHP strpos() function is used to find the position of the first occurrence of a substring within a string. It returns the numeric position if the substring is found, and false if it is not found.
๐ŸŒ
ReqBin
reqbin.com โ€บ code โ€บ php โ€บ menoknaq โ€บ php-string-contains-example
How to check if a string contains a substring in PHP?
MY_STRING; You can use the strpos() ... substring. The strpos() method searches for an occurrence of a substring in a PHP string and returns the index of the first occurrence or "false" otherwise....
๐ŸŒ
Simplilearn
simplilearn.com โ€บ home โ€บ resources โ€บ software development โ€บ strpos in php: syntax, uses and parameter values (with their usecase)
strpos in PHP: Syntax, Uses And Parameter Values (With Their Usecase)
September 14, 2025 - strpos in PHP is a built-in function that finds the first occurrence of a substring in a string. Learn โœ… syntax โœ… uses โœ… parameter values of strpos() function.
Address: 5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
๐ŸŒ
PHP.Watch
php.watch โ€บ versions โ€บ 8.0 โ€บ str_contains
New `str_contains` function - PHP 8.0 โ€ข PHP.Watch
strpos() function returns the position of the needle string, or false if the needle is not found.
๐ŸŒ
Readthedocs
php.readthedocs.io
Synopsis โ€” PHP Doc Test with rST 5.5 documentation
<?php // We can search for the character, ignoring anything before the offset $newstring = 'abcdef abcdef'; $pos = strpos($newstring, 'a', 1); // $pos = 7, not 0 ?> Note ยท This function is binary-safe. stripos ยท strrpos ยท strripos ยท strstr ยท strpbrk ยท substr ยท
๐ŸŒ
Brainly
brainly.in โ€บ computer science โ€บ secondary school
What is the use of strpos() function in php - Brainly.in
June 17, 2020 - It should be noted that this function is binary-safe. strpos is a built-in function in PHP. Its purpose is to locate the first occurrence of a substring within a string or a string within another string.
๐ŸŒ
FlatCoding
flatcoding.com โ€บ home โ€บ php strpos function: how it works with examples
PHP strpos Function: How it Works with Examples - FlatCoding
May 24, 2025 - The PHP strpos function finds the position of text in a string. Click here to see how it works, syntax, and real examples.