Php if contains character

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.
Читайте также:  Https moodle sfedu ru course view php id 20

Examples

Example #1 Using ===

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

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

Источник

Check if String Contains a Character in PHP

This tutorial will discuss about a unique way to check if string contains a character in php.

To check if a string contains a given character or not, we can use the strpos() function. It accepts a string as the first parameter and a substring as a second parameter. Then it returns the index position of the first occurrence of the given substring in the string, whereas, if the given substring does not exist in the string that it returns false.

Now to check if a String Contains a Character, we can pass the string as the first argument and character as a second argument in the strpos() function. If return value is not false, then it means the given character exists in the string.

We have created a separate function for this,

function stringContainsChar($str, $char)

It accept a string and character as an arguments, and returns true if the given character exists in the given string.

Frequently Asked:

Let’s see the complete example,

 $strValue = "Last Train"; $char = "s"; if (stringContainsChar($strValue, $char)) < echo "The string contains the character."; >else < echo "The string does not contain the character."; >?>
The string contains the character.

Summary

We learned how to check if a string contains a character in PHP.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

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