Match substring in php

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

Читайте также:  Convert pages to pdf python

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

Источник

PHP: search substring within a string using preg_match?

1) Its not $patern, its $pattern. 2) You’ve forgotten an $, its not «if (preg_match($substring, string)» it is «if (preg_match($pattern, $string)» & you dont need the else, it can basicly be: «if (preg_match($pattern, $string) < return true; >return false;» because it the if condition is true, the return will be true end this will stop the function, else it will return false and stop the function.

ya this isn’t my actual code, i just wrote a quick example so my bad on the syntax errors. thanks, i mainly just wanted to know how to check for speical characters

2 Answers 2

$pattern = '/' . preg_quote($substring, '/') . '/'; 

This escapes special characters for you. Also pass in ‘/’ so it gets escaped as well since you’re using it as a delimiter.

Another thing, fixes for some typos in your if condition:

if (preg_match($pattern, $string))  

Is there any reason why you want to use preg_match ? Does it have to be a regular expression? What about strpos() ?

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

public static function stringCheck ($string, $substring)

If you don't have a reason to use regular expressions, don't use them.

Regarding the comment about public static : Don't create classes to collect functions (it looks like you are doing this here). That does not make sense. Just create normal functions and include them in your scripts. Use classes for real OOP.
Btw. you should consider a more expressive name for your function. stringCheck is pretty vague (what does it check?).

Источник

Find if substring exists in a string

I always work with strpos since it seems to be the fastest alternative (don't know about regex though).

if(strpos($haystack, $needle) !== FALSE) return $haystack; 

strpos does not return TRUE, but it does return FALSE so you can do if(strpos($haystack, $needle) !== FALSE) return $haystack; and another thing to remember is if you were looking for red then fred would also return a result.

@pathfinder You're absolutely right, seems like I was not paying attention 🙂 Thanks for pointing it out.

This is faster than regex. Also beware that if strpos is case sensitive. If you need to search the substring regardless of case you should use stripos

preg_match_all("/(red|blue|black|white|etc)/", $haystack, $matches); print_r($matches); 

Use a loop for all the strings, and you'll easily notice which of the values from $matches you need.

if you will use strpos then it returns a position of a string it will return a number 1,2,3 etc not true or false.

And the other problem is if string exist at the start it will return 0 which will consider as false then strpos cannot find that word.

strpos or strripos in php should be able to search for a single word in a string. You may have to loop in order to search for all colors if using it though

This question is in a collective: a subcommunity defined by tags with relevant content and experts.

Источник

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