strpos

(PHP 4, PHP 5, PHP 7)

strpos查找字符串首次出现的位置

说明

mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

返回 needlehaystack 中首次出现的数字位置。

参数

haystack

在该字符串中进行查找。

needle

如果 needle 不是一个字符串,那么它将被转换为整型并被视为字符的顺序值。

offset

如果提供了此参数,搜索会从字符串该字符数的起始位置开始统计。 如果是负数,搜索会从字符串结尾指定字符数开始。

返回值

返回 needle 存在于 haystack 字符串起始的位置(独立于 offset)。同时注意字符串位置是从0开始,而不是从1开始的。

如果没找到 needle,将返回 FALSE

Warning

此函数可能返回布尔值 FALSE,但也可能返回等同于 FALSE 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

更新日志

版本 说明
7.1.0 开始支持负数的 offset

范例

Example #1 使用 ===

<?php
$mystring 
'abc';
$findme   'a';
$pos strpos($mystring$findme);

// 注意这里使用的是 ===。简单的 == 不能像我们期待的那样工作,
// 因为 'a' 是第 0 位置上的(第一个)字符。
if ($pos === false) {
    echo 
"The string '$findme' was not found in the string '$mystring'";
} else {
    echo 
"The string '$findme' was found in the string '$mystring'";
    echo 
" and exists at position $pos";
}
?>

Example #2 使用 !==

<?php
$mystring 
'abc';
$findme   'a';
$pos strpos($mystring$findme);

// 使用 !== 操作符。使用 != 不能像我们期待的那样工作,
// 因为 'a' 的位置是 0。语句 (0 != false) 的结果是 false。
if ($pos !== false) {
     echo 
"The string '$findme' was found in the string '$mystring'";
         echo 
" and exists at position $pos";
} else {
     echo 
"The string '$findme' was not found in the string '$mystring'";
}
?>

Example #3 使用位置偏移量

<?php
// 忽视位置偏移量之前的字符进行查找
$newstring 'abcdef abcdef';
$pos strpos($newstring'a'1); // $pos = 7, 不是 0
?>

注释

Note: 此函数可安全用于二进制对象。

参见

  • stripos() - 查找字符串首次出现的位置(不区分大小写)
  • strrpos() - 计算指定字符串在目标字符串中最后一次出现的位置
  • strripos() - 计算指定字符串在目标字符串中最后一次出现的位置(不区分大小写)
  • strstr() - 查找字符串的首次出现
  • strpbrk() - 在字符串中查找一组字符的任何一个字符
  • substr() - 返回字符串的子串
  • preg_match() - 执行匹配正则表达式

User Contributed Notes

greg at spotx dot net 27-Nov-2017 09:48
Warning:
this is not unicode safe

strpos($word,'?') in e?ez-> 1
strpos($word,'?') in è?ent-> 2
Lhenry 03-Oct-2017 06:34
note that strpos( "8 june 1970"  ,  1970 ) returns FALSE..

add quotes to the needle
xcltw1993 at gmail dot com 01-Sep-2017 11:39
Function return false for this case:

<?php
$re
= strpos('1','1,2,3');
var_dump($re);//(bool) false

and?>

 version is 5.3.29, just for me?
eef dot vreeland at gmail dot com 22-Apr-2017 10:16
To prevent others from staring at the text, note that the wording of the 'Return Values' section is ambiguous.

Let's say you have a string $myString containing 50 'a's except on position 3 and 43, they contain 'b'.
And for this moment, forget that counting starts from 0.

strpos($myString, 'b', 40) returns 43, great.

And now the text: "Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset)."

So it doesn't really matter what offset I specify; I'll get the REAL position of the first occurrence in return, which is 3?

... no ...

"independent of offset" means, you will get the REAL positions, thus, not relative to your starting point (offset).

Substract your offset from strpos()'s answer, then you have the position relative to YOUR offset.
jexy dot ru at gmail dot com 23-Jan-2017 05:29
Docs are missing that WARNING is issued if needle is '' (empty string).

In case of empty haystack it just return false:

For example:

<?php
var_dump
(strpos('foo', ''));

var_dump(strpos('', 'foo'));

var_dump(strpos('', ''));
?>

will output:

Warning: strpos(): Empty needle in /in/lADCh on line 3
bool(false)

bool(false)

Warning: strpos(): Empty needle in /in/lADCh on line 7
bool(false)

Note also that warning text may differ depending on php version, see https://3v4l.org/lADCh
m.m.j.kronenburg 07-Sep-2016 07:56
<?php

/**
 * Find the position of the first occurrence of one or more substrings in a
 * string.
 *
 * This function is simulair to function strpos() except that it allows to
 * search for multiple needles at once.
 *
 * @param string $haystack    The string to search in.
 * @param mixed $needles      Array containing needles or string containing
 *                            needle.
 * @param integer $offset     If specified, search will start this number of
 *                            characters counted from the beginning of the
 *                            string.
 * @param boolean $last       If TRUE then the farthest position from the start
 *                            of one of the needles is returned.
 *                            If FALSE then the smallest position from start of
 *                            one of the needles is returned.
 **/
function mstrpos($haystack, $needles, $offset = 0, $last = false)
{
  if(!
is_array($needles)) { $needles = array($needles); }
 
$found = false;
  foreach(
$needles as $needle)
  {
   
$position = strpos($haystack, (string)$needle, $offset);
    if(
$position === false) { continue; }
   
$exp = $last ? ($found === false || $position > $found) :
      (
$found === false || $position < $found);
    if(
$exp) { $found = $position; }
  }
  return
$found;
}

/**
 * Find the position of the first (partially) occurrence of a substring in a
 * string.
 *
 * This function is simulair to function strpos() except that it wil return a
 * position when the substring is partially located at the end of the string.
 *
 * @param string $haystack    The string to search in.
 * @param mixed $needle       The needle to search for.
 * @param integer $offset     If specified, search will start this number of
 *                            characters counted from the beginning of the
 *                            string.
 **/
function pstrpos($haystack, $needle, $offset = 0)
{
 
$position = strpos($haystack, $needle, $offset);
  if(
$position !== false) { return $position; }
 
  for(
$i = strlen($needle); $i > 0; $i--)
  {
    if(
substr($needle, 0, $i) == substr($haystack, -$i))
    { return
strlen($haystack) - $i; }
  }
  return
false;
}

/**
 * Find the position of the first (partially) occurrence of one or more
 * substrings in a string.
 *
 * This function is simulair to function strpos() except that it allows to
 * search for multiple needles at once and it wil return a position when one of
 * the substrings is partially located at the end of the string.
 *
 * @param string $haystack    The string to search in.
 * @param mixed $needles      Array containing needles or string containing
 *                            needle.
 * @param integer $offset     If specified, search will start this number of
 *                            characters counted from the beginning of the
 *                            string.
 * @param boolean $last       If TRUE then the farthest position from the start
 *                            of one of the needles is returned.
 *                            If FALSE then the smallest position from start of
 *                            one of the needles is returned.
 **/
function mpstrpos($haystack, $needles, $offset = 0, $last = false)
{
  if(!
is_array($needles)) { $needles = array($needles); }
 
$found = false;
  foreach(
$needles as $needle)
  {
   
$position = pstrpos($haystack, (string)$needle, $offset);
    if(
$position === false) { continue; }
   
$exp = $last ? ($found === false || $position > $found) :
      (
$found === false || $position < $found);
    if(
$exp) { $found = $position; }
  }
  return
$found;
}

?>
tuxedobob 06-May-2016 02:42
strpos is great for finding the first occurrence of a string, but what if you want the second? Or third?

Easy enough:

<?php
function strposn($haystack, $needle, $num = 1, $offset = 0) {
    for (
$i = 0; $i < $num, $i++) {
       
$x = strpos($haystack, $needle, $offset);
        if (
$x === false) {
            return
false;
        }
       
$offset = $x+strlen($needle);
    }
    return
$x;
}
?>
Anonymous 17-Mar-2016 05:20
## html
# HEading

&nbsp
Click here to go to the support pages.
Click here to submit a bug report.
Click here to request a feature.
(Again, please note, if you ask a question, report a bug, or request a feature, your note will be deleted.)

***heading***
fabio at naoimporta dot com 26-Feb-2016 01:58
It is interesting to be aware of the behavior when the treatment of strings with characters using different encodings.

<?php
# Works like expected. There is no accent
var_dump(strpos("Fabio", 'b'));
#int(2)

# The "á" letter is occupying two positions
var_dump(strpos("Fábio", 'b')) ;
#int(3)

# Now, encoding the string "Fábio" to utf8, we get some "unexpected" outputs. Every letter that is no in regular ASCII table, will use 4 positions(bytes). The starting point remains like before.
# We cant find the characted, because the haystack string is now encoded.
var_dump(strpos(utf8_encode("Fábio"), 'á'));
#bool(false)

# To get the expected result, we need to encode the needle too
var_dump(strpos(utf8_encode("Fábio"), utf8_encode('á')));
#int(1)

# And, like said before, "á" occupies 4 positions(bytes)
var_dump(strpos(utf8_encode("Fábio"), 'b'));
#int(5)
lairdshaw at yahoo dot com dot au 04-Apr-2015 03:02
<?php
/*
 * A strpos variant that accepts an array of $needles - or just a string,
 * so that it can be used as a drop-in replacement for the standard strpos,
 * and in which case it simply wraps around strpos and stripos so as not
 * to reduce performance.
 *
 * The "m" in "strposm" indicates that it accepts *m*ultiple needles.
 *
 * Finds the earliest match of *all* needles. Returns the position of this match
 * or false if none found, as does the standard strpos. Optionally also returns
 * via $match either the matching needle as a string (by default) or the index
 * into $needles of the matching needle (if the STRPOSM_MATCH_AS_INDEX flag is
 * set).
 *
 * Case-insensitive searching can be specified via the STRPOSM_CI flag.
 * Note that for case-insensitive searches, if the STRPOSM_MATCH_AS_INDEX is
 * not set, then $match will be in the haystack's case, not the needle's case,
 * unless the STRPOSM_NC flag is also set.
 *
 * Flags can be combined using the bitwise or operator,
 * e.g. $flags = STRPOSM_CI|STRPOSM_NC
 */
define('STRPOSM_CI'            , 1); // CI => "case insensitive".
define('STRPOSM_NC'            , 2); // NC => "needle case".
define('STRPOSM_MATCH_AS_INDEX', 4);
function
strposm($haystack, $needles, $offset = 0, &$match = null, $flags = 0) {
   
// In the special case where $needles is not an array, simply wrap
    // strpos and stripos for performance reasons.
   
if (!is_array($needles)) {
       
$func = $flags & STRPOSM_CI ? 'stripos' : 'strpos';
       
$pos = $func($haystack, $needles, $offset);
        if (
$pos !== false) {
           
$match = (($flags & STRPOSM_MATCH_AS_INDEX)
                      ?
0
                     
: (($flags & STRPOSM_NC)
                         ?
$needles
                        
: substr($haystack, $pos, strlen($needles))
                        )
                      );
            return
$pos;
        } else    goto
strposm_no_match;
    }

   
// $needles is an array. Proceed appropriately, initially by...
    // ...escaping regular expression meta characters in the needles.
   
$needles_esc = array_map('preg_quote', $needles);
   
// If either of the "needle case" or "match as index" flags are set,
    // then create a sub-match for each escaped needle by enclosing it in
    // parentheses. We use these later to find the index of the matching
    // needle.
   
if (($flags & STRPOSM_NC) || ($flags & STRPOSM_MATCH_AS_INDEX)) {
       
$needles_esc = array_map(
            function(
$needle) {return '('.$needle.')';},
           
$needles_esc
       
);
    }
   
// Create the regular expression pattern to search for all needles.
   
$pattern = '('.implode('|', $needles_esc).')';
   
// If the "case insensitive" flag is set, then modify the regular
    // expression with "i", meaning that the match is "caseless".
   
if ($flags & STRPOSM_CI) $pattern .= 'i';
   
// Find the first match, including its offset.
   
if (preg_match($pattern, $haystack, $matches, PREG_OFFSET_CAPTURE, $offset)) {
       
// Pull the first entry, the overall match, out of the matches array.
       
$found = array_shift($matches);
       
// If we need the index of the matching needle, then...
       
if (($flags & STRPOSM_NC) || ($flags & STRPOSM_MATCH_AS_INDEX)) {
           
// ...find the index of the sub-match that is identical
            // to the overall match that we just pulled out.
            // Because sub-matches are in the same order as needles,
            // this is also the index into $needles of the matching
            // needle.
           
$index = array_search($found, $matches);
        }
       
// If the "match as index" flag is set, then return in $match
        // the matching needle's index, otherwise...
       
$match = (($flags & STRPOSM_MATCH_AS_INDEX)
          ?
$index
         
// ...if the "needle case" flag is set, then index into
          // $needles using the previously-determined index to return
          // in $match the matching needle in needle case, otherwise...
         
: (($flags & STRPOSM_NC)
             ?
$needles[$index]
            
// ...by default, return in $match the matching needle in
             // haystack case.
            
: $found[0]
          )
        );
       
// Return the captured offset.
       
return $found[1];
    }

strposm_no_match:
   
// Nothing matched. Set appropriate return values.
   
$match = ($flags & STRPOSM_MATCH_AS_INDEX) ? false : null;
    return
false;
}
?>
newartix at mail dot ru 31-Mar-2015 08:30
Extend (ohcc at 163 dot com)s comment:

Be careful when the $haystack or $needle parameter is an integer.
If you are not sure of its type, you should  convert it into a string.
<?php
    var_dump
(strpos(12345,1));//false
   
var_dump(strpos(12345,'1'));//0
   
var_dump(strpos('12345',1));//false
   
var_dump(strpos('12345','1'));//0
   
$a = 12345;
   
$b = 1;
   
var_dump(strpos(strval($a),strval($b)));//0
   
var_dump(strpos((string)$a,(string)$b));//0   
   
    // and wait for interesting... CentOS 6.5 PHP-FPM 5.4.35
   
var_dump(strpos('mrwagon',626));//1      tadaaam!
?>
qrworld.net 05-Nov-2014 01:08
I found a function in this post http://softontherocks.blogspot.com/2014/11/buscar-multiples-textos-en-un-texto-con.html
that implements the search in both ways, case sensitive or case insensitive, depending on an input parameter.

The function is:

function getMultiPos($haystack, $needles, $sensitive=true, $offset=0){
    foreach($needles as $needle) {
        $result[$needle] = ($sensitive) ? strpos($haystack, $needle, $offset) : stripos($haystack, $needle, $offset);
    }
    return $result;
}

It was very useful for me.
Andres 19-Jul-2014 05:30
strpos: Want to find lines in text file, NOT beginning with a comment (// for example)?
That way it Works:
$komm=strpos($var,'//');
if($komm === FALSE || $komm == TRUE){}

Generally, it is a nonsense. Why 'strpos' cant ALWAYS output an integer?
ohcc at 163 dot com 27-Jun-2014 07:52
Be careful when the $haystack or $needle parameter is an integer.
If you are not sure of its type, you should  convert it into a string.
<?php
    var_dump
(strpos(12345,1));//false
   
var_dump(strpos(12345,'1'));//0
   
var_dump(strpos('12345',1));//false
   
var_dump(strpos('12345','1'));//0
   
$a = 12345;
   
$b = 1;
   
var_dump(strpos(strval($a),strval($b)));//0
   
var_dump(strpos((string)$a,(string)$b));//0   
?>
andrew dot macrobert+php at gmail dot com 10-Jun-2014 05:30
This function finds ALL occurrences of a substring, returning an array of indexes referring to the start of each occurrence. Overlapping subtrings are not included.
<?php
function strpos_all($haystack, $needle) {
 
$instances = array();

 
$offset = 0;
  while((
$offset = strpos($haystack, $needle, $offset)) !== FALSE) {
   
$instances[] = $offset;
   
$offset += strlen($needle);
  }

  return
$instances;
}
?>
mail at nikha dot org 02-Jun-2014 06:20
What the manual says about "if $needle is not a string" is confusing.

in fact, strpos() compares strings, and nothing else.

Example:
$haystack = "123456789";

$needle = 2;
strpos($haystack, $needle) returns boolean false
$needle = "2";
strpos($haystack, $needle) returns 1;

My real life problem were timestamps. I had a list of timestamps like this: "!<timestamp0>!<timestamp1>!<timestamp2>..." Then I tried to find out, wheter an actualy by "mktime()" generated timestamp is found in this list or not. But strpos() returned always boolean 0, because mktime() results are integers.

It worked only like this:
strpos($timestamp_list, strval($mktime_result))
 
may be helpfull for others...
Niklaus
binodluitel at hotmail dot com 28-Mar-2014 01:26
This function will return 0 if the string that you are searching matches i.e. needle matches the haystack

{code}
echo strpos('bla', 'bla');
{code}

Output: 0
m at binh dot vn 22-Mar-2014 06:04
Using strpos can be tricky sometimes. To reuse it for one search you can use this form:

<?php
$found
= (strpos($haystack, $needle) !== false);
?>

For example:

<?php
$url
= "http://www.binh.vn";
$found = (strpos($url, 'http') !== false);
if (
$found) echo "Found http";
?>

Clearly we see that the position will be 0 but the $found will be true and so we can use more than one time of if ($found) which is much easier.

To further reuse it we could make a very short function:
<?php
function found($haystack, $needle) {
  return (
strpos($haystack, $needle) !== false);
}
?>

Wonder why php didn't have such function for easier use?
harshitpatelrock25 at gmail dot com 18-Dec-2013 07:29
TO find the position specific word in a para:-

<?php
  $String
= 'This is the php language And is Used to develop web programs';
 
$find = '1232';
 
$find_leg = strlen($find);
 
$start_pos = 00;
 
  while(
$string_pos = strpos($String,$find,$start_pos)){
      echo
"<strong> \" $find \" </strong> was found on position : $string_pos <br>" ;
    
$start_pos = $string_pos + $find_leg;
  }
?>
Lurvik 17-Dec-2013 04:02
Don't know if already posted this, but if I did this is an improvement.

This function will check if a string contains  a needle. It _will_ work with arrays and multidimensional arrays (I've tried with a > 16 dimensional array and had no problem).

<?php
function str_contains($haystack, $needles)
{
   
//If needles is an array
   
if(is_array($needles))
    {
       
//go trough all the elements
       
foreach($needles as $needle)
        {
           
//if the needle is also an array (ie needles is a multidimensional array)
           
if(is_array($needle))
            {
               
//call this function again
               
if(str_contains($haystack, $needle))
                {
                   
//Will break out of loop and function.
                   
return true;
                }
               
                return
false;
            }

           
//when the needle is NOT an array:
                //Check if haystack contains the needle, will ignore case and check for whole words only
           
elseif(preg_match("/\b$needle\b/i", $haystack) !== 0)
            {
                return
true;
            }
        }
    }
   
//if $needles is not an array...
   
else
    {
        if(
preg_match("/\b$needles\b/i", $haystack) !== 0)
        {
            return
true;
        }
    }

    return
false;
}
?>
kiipa at live dot com 15-Dec-2013 11:22
So I needed a function to check if a string contains a string. But that also works with arrays. And multidimensional arrays.

Well commented, because I'm sharing the source I use this in.

<?php
private static $found;
//Sees if a string contains another string, WORKS WITH 2D ARRAYS! Returns true or false.
public static function strcont($haystack, $needles)
{
   
//If needles is an array
   
if(is_array($needles))
    {
       
//go trough all the elements
       
foreach($needles as $needle)
        {
           
//if the needle is also an array (ie needles is a multidimensional array)
           
if(is_array($needle))
            {
               
//call this function again
               
static::strcont($haystack, $needle);
            }
           
//when the needle is NOT an array:
           
elseif(strpos($haystack, $needle) !== false)
            {
               
//Set the bool to true (DO NOT CHANGE TO return true). IT WILL NOT WORK!
               
static::$found = true;
            }
        }

       
//Because we only set the bool if we found something we'll check if the bool is set.
       
if(isset(static::$found))
        {
           
//Then return true.
           
return true;
        }
       
        return
false;
    }
   
//If the needles is not an array (this function can be used as strpos...)
   
else
    {
        if(
strpos($haystack, $needles) !== false)
        {
            return
true;
        }
       
        return
falsE;
    }
}   
?>
Anonymous 19-Feb-2013 06:55
The most straightforward way to prevent this function from returning 0 is:

  strpos('x'.$haystack, $needle, 1)

The 'x' is simply a garbage character which is only there to move everything 1 position.
The number 1 is there to make sure that this 'x' is ignored in the search.
This way, if $haystack starts with $needle, then the function returns 1 (rather than 0).
mtroy dot student at gmail dot com 26-Apr-2012 01:46
when you want to know how much of substring occurrences, you'll use "substr_count".
But, retrieve their positions, will be harder.
So, you can do it by starting with the last occurrence :

function strpos_r($haystack, $needle)
{
    if(strlen($needle) > strlen($haystack))
        trigger_error(sprintf("%s: length of argument 2 must be <= argument 1", __FUNCTION__), E_USER_WARNING);

    $seeks = array();
    while($seek = strrpos($haystack, $needle))
    {
        array_push($seeks, $seek);
        $haystack = substr($haystack, 0, $seek);
    }
    return $seeks;
}

it will return an array of all occurrences a the substring in the string

Example :

$test = "this is a test for testing a test function... blah blah";
var_dump(strpos_r($test, "test"));

// output

array(3) {
  [0]=>
  int(29)
  [1]=>
  int(19)
  [2]=>
  int(10)
}

Paul-antoine
Malézieux.
martijn at martijnfrazer dot nl 26-Feb-2012 12:58
This is a function I wrote to find all occurrences of a string, using strpos recursively.

<?php
function strpos_recursive($haystack, $needle, $offset = 0, &$results = array()) {               
   
$offset = strpos($haystack, $needle, $offset);
    if(
$offset === false) {
        return
$results;           
    } else {
       
$results[] = $offset;
        return
strpos_recursive($haystack, $needle, ($offset + 1), $results);
    }
}
?>

This is how you use it:

<?php
$string
= 'This is some string';
$search = 'a';
$found = strpos_recursive($string, $search);

if(
$found) {
    foreach(
$found as $pos) {
        echo
'Found "'.$search.'" in string "'.$string.'" at position <b>'.$pos.'</b><br />';
    }   
} else {
    echo
'"'.$search.'" not found in "'.$string.'"';
}
?>
rjeggens at ijskoud dot org 24-Jan-2012 04:38
I lost an hour before I noticed that strpos only returns FALSE as a boolean, never TRUE.. This means that

strpos() !== false

is a different beast then:

strpos() === true

since the latter will never be true. After I found out, The warning in the documentation made a lot more sense.
gjh42 - simonokewode at hotmail dot com 08-Nov-2011 04:59
A pair of functions to replace every nth occurrence of a string with another string, starting at any position in the haystack. The first works on a string and the second works on a single-level array of strings, treating it as a single string for replacement purposes (any needles split over two array elements are ignored).

Can be used for formatting dynamically-generated HTML output without touching the original generator: e.g. add a newLine class tag to every third item in a floated list, starting with the fourth item.
 
<?php
/* String Replace at Intervals   by Glenn Herbert (gjh42)    2010-12-17
 */
 
//(basic locator by someone else - name unknown)
//strnposr() - Find the position of nth needle in haystack.
function strnposr($haystack, $needle, $occurrence, $pos = 0) {
    return (
$occurrence<2)?strpos($haystack, $needle, $pos):strnposr($haystack,$needle,$occurrence-1,strpos($haystack, $needle, $pos) + 1);
}

//gjh42
//replace every nth occurrence of $needle with $repl, starting from any position
function str_replace_int($needle, $repl, $haystack, $interval, $first=1, $pos=0) {
  if (
$pos >= strlen($haystack) or substr_count($haystack, $needle, $pos) < $first) return $haystack;
 
$firstpos = strnposr($haystack, $needle, $first, $pos);
 
$nl = strlen($needle);
 
$qty = floor(substr_count($haystack, $needle, $firstpos + 1)/$interval);
  do {
//in reverse order
   
$nextpos = strnposr($haystack, $needle, ($qty * $interval) + 1, $firstpos);
   
$qty--;
   
$haystack = substr_replace($haystack, $repl, $nextpos, $nl);
  } while (
$nextpos > $firstpos);
  return
$haystack;
}
 
//$needle = string to find
  //$repl = string to replace needle
  //$haystack = string to do replacing in
  //$interval = number of needles in loop
  //$first=1 = first occurrence of needle to replace (defaults to first)
  //$pos=0 = position in haystack string to start from (defaults to first)
 
//replace every nth occurrence of $needle with $repl, starting from any position, in a single-level array
function arr_replace_int($needle, $repl, $arr, $interval, $first=1, $pos=0, $glue='|+|') {
  if (!
is_array($arr))  return $arr;
  foreach(
$arr as $key=>$value){
    if (
is_array($arr[$key])) return $arr;
  }
 
$haystack = implode($glue, $arr);
 
$haystack = str_replace_int($needle, $repl, $haystack, $interval, $first, $pos);
 
$tarr = explode($glue, $haystack);
 
$i = 0;
  foreach(
$arr as $key=>$value){
   
$arr[$key] = $tarr[$i];
   
$i++;
  }
  return
$arr;
}
?>
If $arr is not an array, or a multilevel array, it is returned unchanged.
jim at terrys dot net 30-Sep-2011 08:53
strpos that accepts an array for $needle

<?php
// strpos that takes an array of values to match against a string
// note the stupid argument order (to match strpos)
function strpos_arr($haystack, $needle) {
    if(!
is_array($needle)) $needle = array($needle);
    foreach(
$needle as $what) {
        if((
$pos = strpos($haystack, $what))!==false) return $pos;
    }
    return
false;
}
?>
akarmenia at gmail dot com 05-Mar-2011 01:44
My version of strpos with needles as an array. Also allows for a string, or an array inside an array.

<?php
function strpos_array($haystack, $needles) {
    if (
is_array($needles) ) {
        foreach (
$needles as $str) {
            if (
is_array($str) ) {
               
$pos = strpos_array($haystack, $str);
            } else {
               
$pos = strpos($haystack, $str);
            }
            if (
$pos !== FALSE) {
                return
$pos;
            }
        }
    } else {
        return
strpos($haystack, $needles);
    }
}

// Test
echo strpos_array('This is a test', array('test', 'drive')); // Output is 10

?>
Anonymous 19-Aug-2010 11:50
Beware the mindless "if needle is not string":

# php -r 'var_dump(strpos("X1234567",5));'
bool(false)
# php -r 'var_dump(strpos("X1234567","5"));'
int(5)
gambajaja at yahoo dot com 18-Aug-2010 12:25
<?php
$my_array
= array ('100,101', '200,201', '300,301');
$check_me_in = array ('100','200','300','400');
foreach (
$check_me_in as $value_cmi){
   
$is_in=FALSE; #asume that $check_me_in isn't in $my_array
   
foreach ($my_array as $value_my){
       
$pos = strpos($value_my, $value_cmi);
        if (
$pos===0)
           
$pos++;
        if (
$pos==TRUE){
           
$is_in=TRUE;
           
$value_my2=$value_my;
            }
    }
    if (
$is_in) echo "ID $value_cmi in \$check_me_in I found in value '$value_my2' \n";
}
?>

The above example will output
ID 100 in $check_me_in I found in value '100,101'
ID 200 in $check_me_in I found in value '200,201'
ID 300 in $check_me_in I found in value '300,301'
usulaco at gmail dot com 11-Aug-2010 02:04
Parse strings between two others in to array.

<?php
function g($string,$start,$end){
    
preg_match_all('/' . preg_quote($start, '/') . '(.*?)'. preg_quote($end, '/').'/i', $string, $m);
    
$out = array();

     foreach(
$m[1] as $key => $value){
      
$type = explode('::',$value);
       if(
sizeof($type)>1){
          if(!
is_array($out[$type[0]]))
            
$out[$type[0]] = array();
         
$out[$type[0]][] = $type[1];
       } else {
         
$out[] = $value;
       }
     }
  return
$out;
}
print_r(g('Sample text, [/text to extract/] Rest of sample text [/WEB::http://google.com/] bla bla bla. ','[/','/]'));
?>

results:
Array
(
    [0] => text to extract
    [WEB] => Array
        (
            [0] => http://google.com
        )

)

Can be helpfull to custom parsing :)
olmstead31 at yahoo dot com 23-Mar-2010 04:48
I found that whatever I was using as a test with strpos it came out false exept if $pos was == 1

I figured it gives me a numeric value if found else it is null or false
here is what i did to make my code work:

<?php
//EXAMPLE 1:
$quiamime = ',64,68,70,';
$me = '64'
$posi = strpos($quiaime, ",$me,");  //posi is equal to 0
if (!is_numeric($posi)){
 
//code here
}else{
 
//else code here
}

//EXAMPLE 2:
$quiamime = ',68,70,64,';
$me = '64'
$posi = strpos($quiaime, ",$me,");  //posi is equal to 6
if (!is_numeric($posi)){
 
//code here
}else{
 
//else code here
}

//EXAMPLE 3:
$quiamime = ',68,70,';
$me = '64'
$posi = strpos($quiaime, ",$me,");  //posi is equal to NULL or FALSE
if (!is_numeric($posi)){
 
//code here
}else{
 
//else code here
}
?>
daevid at daevid dot com 26-Jan-2010 11:46
Dan Brown and I had a discussion on the PHP list about the speed difference between the popular three string searching techniques. He wrote a simple timing test, and I adapted it further. The end result is that all three are very close and not even noticeable for sets < 1M. Although, technically strpos() is about twice as fast (as the docs allude to above). Here it is for your own amusement and testing purposes.

<?php
for ($i = 0; $i < 1000000; $i++ )
   
$o[] =
sprintf('%04d-%02d-%02d',rand(0000,9999),rand(00,99),rand(00,99));
#print_r($o);
echo "array of ".number_format($i)."\n";
###################################################################
$now = microtime(true);
for(
$i=0;$i<count($o);$i++) {
       if(
preg_match('/^[0]{4,}\-/U',$o[$i])) {
              
//echo "Offset #".$i." matches: ".$o[$i].PHP_EOL;
      
}
}
$rank['preg_match'] = (microtime(true) - $now);
###################################################################
$later = microtime(true);
for(
$i=0;$i<count($o);$i++) {
        if(
substr($o[$i],0,4) == "0000") {
               
//echo "Offset #".$i." matches: ".$o[$i].PHP_EOL;
       
}
}
$rank['substr'] = (microtime(true) - $later);
###################################################################
$after = microtime(true);
for(
$i=0;$i<count($o);$i++) {
        if(
strpos($o[$i], '0000') === 0) {
               
//echo "Offset #".$i." matches: ".$o[$i].PHP_EOL;
       
}
}
$rank['strpos'] = (microtime(true) - $after);
###################################################################
asort($rank);
print_r($rank);
?>

array of 10,000
Array
(
    [strpos] => 0.00766682624817
    [substr] => 0.0116670131683
    [preg_match] => 0.0124950408936
)

array of 100,000
Array
(
    [strpos] => 0.0817799568176
    [substr] => 0.120522975922
    [preg_match] => 0.125612974167
)

array of 1,000,000
Array
(
    [strpos] => 0.805890083313
    [substr] => 1.19799995422
    [preg_match] => 1.25615906715
)

I ran out of memory with more than 1M array elements.
Achintya 06-Nov-2009 11:03
A function I made to find the first occurrence of a particular needle not enclosed in quotes(single or double). Works for simple nesting (no backslashed nesting allowed).

<?php
function strposq($haystack, $needle, $offset = 0){
   
$len = strlen($haystack);
   
$charlen = strlen($needle);
   
$flag1 = false;
   
$flag2 = false;
    for(
$i = $offset; $i < $len; $i++){
        if(
substr($haystack, $i, 1) == "'"){
           
$flag1 = !$flag1 && !$flag2 ? true : false;
        }
        if(
substr($haystack, $i, 1) == '"'){
           
$flag2 = !$flag1 && !$flag2 ? true : false;
        }
        if(
substr($haystack, $i, $charlen) == $needle && !$flag1 && !$flag2){
            return
$i;       
        }
    }
    return
false;
}

echo
strposq("he'llo'character;\"'som\"e;crap", ";"); //16
?>
yasindagli at gmail dot com 05-Oct-2009 06:05
This function finds postion of nth occurence of a letter starting from offset.

<?php
function nth_position($str, $letter, $n, $offset = 0){
   
$str_arr = str_split($str);
   
$letter_size = array_count_values(str_split(substr($str, $offset)));
    if( !isset(
$letter_size[$letter])){
       
trigger_error('letter "' . $letter . '" does not exist in ' . $str . ' after ' . $offset . '. position', E_USER_WARNING);
        return
false;
    } else if(
$letter_size[$letter] < $n) {
       
trigger_error('letter "' . $letter . '" does not exist ' . $n .' times in ' . $str . ' after ' . $offset . '. position', E_USER_WARNING);
        return
false;
    }
    for(
$i = $offset, $x = 0, $count = (count($str_arr) - $offset); $i < $count, $x != $n; $i++){
        if(
$str_arr[$i] == $letter){
           
$x++;
        }
    }
    return
$i - 1;
}

echo
nth_position('foobarbaz', 'a', 2); //7
echo nth_position('foobarbaz', 'b', 1, 4); //6
?>
digitalpbk [at] gmail.com 01-Oct-2009 05:37
This function raises a warning if the offset is not between 0 and the length of string:

Warning: strpos(): Offset not contained in string in %s on line %d
ah dot d at hotmail dot com 11-Aug-2009 10:29
A strpos modification to return an array of all the positions of a needle in the haystack

<?php
function strallpos($haystack,$needle,$offset = 0){
   
$result = array();
    for(
$i = $offset; $i<strlen($haystack); $i++){
       
$pos = strpos($haystack,$needle,$i);
        if(
$pos !== FALSE){
           
$offset $pos;
            if(
$offset >= $i){
               
$i = $offset;
               
$result[] = $offset;
            }
        }
    }
    return
$result;
}
?>

example:-

<?php
$haystack
= "ASD is trying to get out of the ASDs cube but the other ASDs told him that his behavior will destroy the ASDs world";

$needle = "ASD";

print_r(strallpos($haystack,$needle));

//getting all the positions starting from a specified position

print_r(strallpos($haystack,$needle,34));
?>
teddanzig at yahoo dot com 23-Mar-2009 06:48
routine to return -1 if there is no match for strpos

<?php
//instr function to mimic vb instr fucntion
function InStr($haystack, $needle)
{
   
$pos=strpos($haystack, $needle);
    if (
$pos !== false)
    {
        return
$pos;
    }
    else
    {
        return -
1;
    }
}
?>
jburns131 at jbwebware dot com 28-Dec-2008 01:48
The Situation:

I wanted to return TRUE if strpos returned position 0, and only position 0, without the added overhead of preg_match.

The Solution:

As PHP treats 0 (zero) as NULL, and strpos returns the int 0 (but not NULL), I used type casting and the "===" comparison operator (as it compares types) to resolve my issue.

<?php

$hayStack
= "dbHost";
$needle  = "db"
$needlePos = strpos($hayStack, $needle);

if((string)
$needlePos === (string)0) {
    echo
"db is in position zero";
} else {
    echo
"db is NOT in position zero";
}

?>

Returns:
db is in position zero

<?php

$hayStack
= "another_db_host";
$needle  = "db"
$needlePos = strpos($hayStack, $needle);

if((string)
$needlePos === (string)0) {
    echo
"db is in position zero";
} else {
    echo
"db is NOT in position zero";
}

?>

This returns:
db is in NOT position zero
Tim 18-Nov-2008 02:52
If you would like to find all occurences of a needle inside a haystack you could use this function strposall($haystack,$needle);. It will return an array with all the strpos's.

<?php
/**
 * strposall
 *
 * Find all occurrences of a needle in a haystack
 *
 * @param string $haystack
 * @param string $needle
 * @return array or false
 */
function strposall($haystack,$needle){
   
   
$s=0;
   
$i=0;
   
    while (
is_integer($i)){
       
       
$i = strpos($haystack,$needle,$s);
       
        if (
is_integer($i)) {
           
$aStrPos[] = $i;
           
$s = $i+strlen($needle);
        }
    }
    if (isset(
$aStrPos)) {
        return
$aStrPos;
    }
    else {
        return
false;
    }
}
?>
mickRacky 19-Sep-2008 08:17
here's a php implementation of stdc++ string class find_first_of using strpos.

<?php
function find_first_of($haystack, $needlesAsString, $offset=0)
{
 
$max = strlen($needlesAsString);
 
$index = strlen($haystack)+1;
  for(
$ii=0; $ii<$max;$ii++){
   
$result = strpos($haystack,$needlesAsString[$ii], $offset);
    if(
$result !== FALSE  && $result < $index)
     
$index = $result;
  }
  return (
$index > strlen($haystack)? FALSE: $index);
}
?>

Example:
<?php
$test
="Ralph: One of these days, Alice!!";
$look_for=":!,";   // punctuation marks

$ss = 0;
while(
$answer=find_first_of($test,$look_for,$ss) ) {
  echo
$answer . "\n";
 
$ss = $answer+1;
 }
?>

This prints out:
5
24
31
32
paul at thiswayupdesign dot co dot uk 18-Jun-2008 12:48
I wasn't aware of the !== operator, only the === for false. I was using this code on strpos:

<?php
while( ! ($start=@strpos($source,$startTag,$end)) === false) {
 
// ...
}
?>

This gave a false if the string was found at position 0, which is weird.

However using

<?php
while(($start=@strpos($source,$startTag,$end)) !== false) {
 
// ...
}
?>

Gives no such error and seems to work correctly
ilaymyhat-rem0ve at yahoo dot com 02-Apr-2008 01:17
This might be useful.

<?php
class String{
   
   
//Look for a $needle in $haystack in any position
   
public static function contains(&$haystack, &$needle, &$offset)
    {
       
$result = strpos($haystack, $needle, $offset);
        return
$result !== FALSE;
    }
   
   
//intuitive implementation .. if not found returns -1.
   
public static function strpos(&$haystack, &$needle, &$offset)
    {
       
$result = strpos($haystack, $needle, $offset);
        if (
$result === FALSE )
        {
            return -
1;
        }
        return
$result;
    }
   
}
//String
?>
Suggested re-write for pink WARNING box 12-Jan-2008 12:45
WARNING

As strpos may return either FALSE (substring absent) or 0 (substring at start of string), strict versus loose equivalency operators must be used very carefully.

To know that a substring is absent, you must use: 

=== FALSE

To know that a substring is present (in any position including 0), you can use either of:

!== FALSE  (recommended)
 > -1  (note: or greater than any negative number)

To know that a substring is at the start of the string, you must use: 

=== 0

To know that a substring is in any position other than the start, you can use any of:

 > 0  (recommended)
!= 0  (note: but not !== 0 which also equates to FALSE)
!= FALSE  (disrecommended as highly confusing)

Also note that you cannot compare a value of "" to the returned value of strpos. With a loose equivalence operator (== or !=) it will return results which don't distinguish between the substring's presence versus position. With a strict equivalence operator (=== or !==) it will always return false.
user at nomail dot com 15-May-2007 11:21
This is a bit more useful when scanning a large string for all occurances between 'tags'.

<?php
function getStrsBetween($s,$s1,$s2=false,$offset=0) {
   
/*====================================================================
    Function to scan a string for items encapsulated within a pair of tags

    getStrsBetween(string, tag1, <tag2>, <offset>

    If no second tag is specified, then match between identical tags

    Returns an array indexed with the encapsulated text, which is in turn
    a sub-array, containing the position of each item.

    Notes:
    strpos($needle,$haystack,$offset)
    substr($string,$start,$length)

    ====================================================================*/

   
if( $s2 === false ) { $s2 = $s1; }
   
$result = array();
   
$L1 = strlen($s1);
   
$L2 = strlen($s2);

    if(
$L1==0 || $L2==0 ) {
        return
false;
    }

    do {
       
$pos1 = strpos($s,$s1,$offset);

        if(
$pos1 !== false ) {
           
$pos1 += $L1;

           
$pos2 = strpos($s,$s2,$pos1);

            if(
$pos2 !== false ) {
               
$key_len = $pos2 - $pos1;

               
$this_key = substr($s,$pos1,$key_len);

                if( !
array_key_exists($this_key,$result) ) {
                   
$result[$this_key] = array();
                }

               
$result[$this_key][] = $pos1;

               
$offset = $pos2 + $L2;
            } else {
               
$pos1 = false;
            }
        }
    } while(
$pos1 !== false );

    return
$result;
}
?>
gal_chen123 at hotmail dot co dot il 03-Apr-2007 06:57
this function returns the text between 2 strings:

<?php
function get_between ($text, $s1, $s2) {
   
$mid_url = "";
   
$pos_s = strpos($text,$s1);
   
$pos_e = strpos($text,$s2);
    for (
$i=$pos_s+strlen($s1) ; ( ( $i < ($pos_e)) && $i < strlen($text) ) ; $i++ ) {
       
$mid_url .= $text[$i];
    }
    return
$mid_url;
}
?>

if $s1 or $s2 are not found, $mid_url will be empty
to add an offset, simply compare $pos_s to the offset, and only let it continue if the offset is smaller then $pos_s.
spinicrus at gmail dot com 14-Oct-2006 07:58
if you want to get the position of a substring relative to a substring of your string, BUT in REVERSE way:

<?php

function strpos_reverse_way($string,$charToFind,$relativeChar) {
   
//
   
$relativePos = strpos($string,$relativeChar);
   
$searchPos = $relativePos;
   
$searchChar = '';
   
//
   
while ($searchChar != $charToFind) {
       
$newPos = $searchPos-1;
       
$searchChar = substr($string,$newPos,strlen($charToFind));
       
$searchPos = $newPos;
    }
   
//
   
if (!empty($searchChar)) {
       
//
       
return $searchPos;
        return
TRUE;
    }
    else {
        return
FALSE;
    }
   
//
}

?>
dale at ucsc dot edu 11-Nov-2005 11:28
if you want need a fast function to find the first occurrence of any ch element of an needle array this function might be of use:
<?php
$eurl
= strpos_needle_array($text, array('"'=>0,'\''=>0,'>'=>0, ' '=>0, "\n"=>0), $surl);

function
strpos_needle_array(& $text, $needle_ary, $offset=0){   
    for(
$ch_pos=$offset;$ch_pos<strlen($text);$ch_pos++){
        if(isset(
$needle_ary[$text[$ch_pos]])){
            return
$ch_pos;
        }
    }
    return
false;
}
?>
arias at elleondeoro dot com 07-Feb-2005 03:33
If you want to get all positions in an array, you can use this function. If the optional parameter count is especified, the function will put there the number of matches.

<?php
function strallpos($pajar, $aguja, $offset=0, &$count=null) {
  if (
$offset > strlen($pajar)) trigger_error("strallpos(): Offset not contained in string.", E_USER_WARNING);
 
$match = array();
  for (
$count=0; (($pos = strpos($pajar, $aguja, $offset)) !== false); $count++) {
   
$match[] = $pos;
   
$offset = $pos + strlen($aguja);
  }
  return
$match;
}
?>
philip 26-Aug-2004 12:52
Many people look for in_string which does not exist in PHP, so, here's the most efficient form of in_string() (that works in both PHP 4/5) that I can think of:
<?php
function in_string($needle, $haystack, $insensitive = false) {
    if (
$insensitive) {
        return
false !== stristr($haystack, $needle);
    } else {
        return
false !== strpos($haystack, $needle);
    }
}
?>
bishop 22-Apr-2004 12:38
Code like this:
<?php
if (strpos('this is a test', 'is') !== false) {
    echo
"found it";
}
?>

gets repetitive, is not very self-explanatory, and most people handle it incorrectly anyway. Make your life easier:

<?php
function str_contains($haystack, $needle, $ignoreCase = false) {
    if (
$ignoreCase) {
       
$haystack = strtolower($haystack);
       
$needle   = strtolower($needle);
    }
   
$needlePos = strpos($haystack, $needle);
    return (
$needlePos === false ? false : ($needlePos+1));
}
?>

Then, you may do:
<?php
// simplest use
if (str_contains('this is a test', 'is')) {
    echo
"Found it";
}

// when you need the position, as well whether it's present
$needlePos = str_contains('this is a test', 'is');
if (
$needlePos) {
    echo
'Found it at position ' . ($needlePos-1);
}

// you may also ignore case
$needlePos = str_contains('this is a test', 'IS', true);
if (
$needlePos) {
    echo
'Found it at position ' . ($needlePos-1);
}
?>