[Osaka/Yokohama/Tokushima] Looking for infrastructure/server side engineers!

[Osaka/Yokohama/Tokushima] Looking for infrastructure/server side engineers!

[Deployed by over 500 companies] AWS construction, operation, maintenance, and monitoring services

[Deployed by over 500 companies] AWS construction, operation, maintenance, and monitoring services

[Successor to CentOS] AlmaLinux OS server construction/migration service

[Successor to CentOS] AlmaLinux OS server construction/migration service

[For WordPress only] Cloud server “Web Speed”

[For WordPress only] Cloud server “Web Speed”

[Cheap] Website security automatic diagnosis “Quick Scanner”

[Cheap] Website security automatic diagnosis “Quick Scanner”

[Reservation system development] EDISONE customization development service

[Reservation system development] EDISONE customization development service

[Registration of 100 URLs is 0 yen] Website monitoring service “Appmill”

[Registration of 100 URLs is 0 yen] Website monitoring service “Appmill”

[Compatible with over 200 countries] Global eSIM “Beyond SIM”

[Compatible with over 200 countries] Global eSIM “Beyond SIM”

[If you are traveling, business trip, or stationed in China] Chinese SIM service “Choco SIM”

[If you are traveling, business trip, or stationed in China] Chinese SIM service “Choco SIM”

[Global exclusive service] Beyond's MSP in North America and China

[Global exclusive service] Beyond's MSP in North America and China

[YouTube] Beyond official channel “Biyomaru Channel”

[YouTube] Beyond official channel “Biyomaru Channel”

[PHP] Points to note when checking whether a specified string/pattern is included

PHP

Introduction

This is Kusakabe from the WEB team.
I often forget what the return value of strpos() or preg_match() is and look it up, so I've summarized it with some simple notes as a reminder.
The focus is only on whether the specified string/pattern is included, and only some functions are explained, so please refer to the manual for details on each function.

What can be said overall

When comparing values, use ===, !== instead of ==, != unless you have a good reason to do so.
Especially if you find it surprising that 0 == FALSE becomes TRUE, we recommend that you look at the type comparison table

table of contents

  • Check if it contains the specified string
  • Check if it contains the specified pattern
  • Extract elements that match a pattern from an array

Check if it contains the specified string

strpos() [ Manual ]

int strpos(string $heystack, mixed $needle)

argument

heystack: String to search for.
needle: String to search for. It is also possible to specify types other than strings...(described later)

return value

Returns the position where needle first appears in heystack (starting at 0).
If needle is not included in heystack, it returns FALSE, so

strpos($heystack, $needle) !== FALSE

Existence can be checked by looking at the value of .

Note 1

If needle appears at the beginning of heystack, the return value is 0.

strpos($heystack, $needle) != FALSE

becomes FALSE when "the string appears at the beginning". Be sure to also compare types.

Note 2

to the manual

If needle is not a string, convert it to an integer and treat it as the character corresponding to that number.

However, this
does not
mean that "if needle is not a string, cast it to an integer and then cast it to a string." (Casting to an integer is correct.)
If needle is not a string, the needle cast to an integer is treated as a character corresponding to a decimal ASCII code.
In other words, the following two are not equivalent,

strpos('2100', 100) strpos('2100', (string)(int)100) // needle becomes string 100

The following three are equivalent:

strpos('2100', 100) strpos('2100', chr((int)100)) strpos('2100', 'd')

To avoid unintended consequences, it is best to specify a string for needle unless there are special circumstances.
Click here for chr()
PHP: chr - Manual

Note 3

If you insert an array into needle, it will not cause an error, but this does not mean that you can specify multiple needles; the array will simply be cast to an integer.

#As of PHP 7.0, casting an array to an integer will result in 0 for an empty array and 1 for a non-empty array.


strstr() [ Manual ]

This function finds the first occurrence of needle and returns from there to the end of the string.
If needle is not found, it returns FALSE, so it can be used to check for existence, but it is not recommended to use this function solely for that purpose.

Note:
If you just want to check whether a needle exists in a particular haystack, use strpos() instead, which is faster and uses less memory.


Check if it contains the specified pattern

preg_match() [ Manual ]

int preg_match(string $pattern, string $subject)

return value

Returns 1 if there is a string matching pattern in the subject, 0 otherwise, and FALSE if an error occurs in the matching process. When checking the existence of

preg_match($pattern, $subject) === 1

All you have to do is check if is TRUE.

Points to note

If you need to distinguish between no match and an error, be aware that 0 == FALSE becomes TRUE.


Extract elements that match a pattern from an array

Here the array

$input = ['first', 'second', 'third', 'fourth', 'fifth'];

Consider an example of extracting elements that end with th from .
An easy way to do this is to use preg_grep().

preg_grep() [ Manual ]

array preg_grep(string $pattern, array $input)

return value

of an array that extracts elements that match pattern from input elements
:

preg_grep('/th$/', $input) // ['fourth', 'fifth']

this is

array_filter($input, function($s) { return preg_match('/th$/', $s) === 1; })

is equivalent to

Points to note

If you specify the constant PREG_GREP_INVERT as the third argument of preg_grep(), that do not match will be extracted. It is also extracted when matching processing results in an error. In other words, the following two are equivalent.

preg_grep('/th$/', $input, PREG_GREP_INVERT) array_filter($input, function($s) { return preg_match('/th$/', $s) !== 1; })

#There is no constant defined to explicitly specify "extract elements that match the pattern", so if you want to extract matching elements, omit the third argument or specify 0.

If you found this article helpful , please give it a like!
2
Loading...
2 votes, average: 1.00 / 12
7,809
X facebook Hatena Bookmark pocket
[2025.6.30 Amazon Linux 2 support ended] Amazon Linux server migration solution

[2025.6.30 Amazon Linux 2 support ended] Amazon Linux server migration solution

The person who wrote this article

About the author