Php search substring in string

strpos

Find the numeric position of the first occurrence of needle in the haystack string.

Parameters

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. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

If specified, search will start this number of characters counted from the beginning of the string. If the offset is negative, the search will start this number of characters counted from the end of the string.

Return Values

Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.

Returns false if the needle was not found.

This function may return Boolean false , but may also return a non-Boolean value which evaluates to false . Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Changelog

Version Description
8.0.0 Passing an int as needle is no longer supported.
7.3.0 Passing an int as needle has been deprecated.
7.1.0 Support for negative offset s has been added.

Examples

Example #1 Using ===

$mystring = ‘abc’ ;
$findme = ‘a’ ;
$pos = strpos ( $mystring , $findme );

Читайте также:  Обработчики событий javascript код

// Note our use of ===. Simply == would not work as expected
// because the position of ‘a’ was the 0th (first) character.
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 Using !==

$mystring = ‘abc’ ;
$findme = ‘a’ ;
$pos = strpos ( $mystring , $findme );

// The !== operator can also be used. Using != would not work as expected
// because the position of ‘a’ is 0. The statement (0 != false) evaluates
// to 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 Using an offset

// We can search for the character, ignoring anything before the offset
$newstring = ‘abcdef abcdef’ ;
$pos = strpos ( $newstring , ‘a’ , 1 ); // $pos = 7, not 0
?>

Notes

Note: This function is binary-safe.

See Also

  • stripos() — Find the position of the first occurrence of a case-insensitive substring in a string
  • str_contains() — Determine if a string contains a given substring
  • str_ends_with() — Checks if a string ends with a given substring
  • str_starts_with() — Checks if a string starts with a given substring
  • strrpos() — Find the position of the last occurrence of a substring in a string
  • strripos() — Find the position of the last occurrence of a case-insensitive substring in a string
  • strstr() — Find the first occurrence of a string
  • strpbrk() — Search a string for any of a set of characters
  • substr() — Return part of a string
  • preg_match() — Perform a regular expression match

User Contributed Notes 38 notes

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:

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:

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.

It is interesting to be aware of the behavior when the treatment of strings with characters using different encodings.

# 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)

This is a function I wrote to find all occurrences of a string, using strpos recursively.

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:

$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 ‘ . $pos . ‘
‘ ;
>
> else echo ‘»‘ . $search . ‘» not found in «‘ . $string . ‘»‘ ;
>
?>

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

$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

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

I lost an hour before I noticed that strpos only returns FALSE as a boolean, never TRUE.. This means that

is a different beast then:

since the latter will never be true. After I found out, The warning in the documentation made a lot more sense.

/**
* 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 )

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 ;
>

Источник

Оцените статью