Home  >  Article  >  Backend Development  >  How to compare strings in php (case insensitive)

How to compare strings in php (case insensitive)

青灯夜游
青灯夜游Original
2021-06-02 17:50:415344browse

PHP method of comparing strings without case sensitivity: 1. Use the "strcasecmp(String 1, String 2)" statement; 2. Use the "strnatcasecmp (String 1, String 2)" statement ;3. Use the "strncasecmp(String 1, String 2, length)" statement.

How to compare strings in php (case insensitive)

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

Method 1: Use strcasecmp()--Case insensitive

strcasecmp() function compares two strings. The syntax is as follows

strcasecmp(string1,string2)
##ParameterDescriptionRequired. Specifies the first string to compare. Required. Specifies the second string to be compared.
string1
string2
Return value:


  • 0 - If the two strings are equal

  • 8f029751ac12f19769820fc6523b37120 - if string1 is greater than string2

Example:

<?php
echo strcasecmp("Hello world!","HELLO WORLD!");
?>

Output:

0

Method 2: Use strnatcasecmp() function--case insensitive

strnatcasecmp The () function uses a "natural" algorithm to compare two strings (case-insensitive).

In natural algorithms, the number 2 is less than the number 10. In computer sorting, 10 is less than 2 because the first number in 10 is less than 2.

Syntax:

strnatcasecmp(string1,string2)

Return value:


  • 0 - If the two strings are equal

  • 8f029751ac12f19769820fc6523b37120 - if string1 is greater than string2

Example:

<?php
echo strnatcasecmp("2Hello world!","10Hello WORLD!");
echo "<br>";
echo strnatcasecmp("10Hello world!","2Hello WORLD!");
?>

Output:


-1
1

Method 2: Use strncasecmp() function--case insensitive

strncasecmp() function compares two strings (case-insensitive). The syntax is as follows

strncasecmp(string1,string2,length)

##Parameterstring1string2length Return value:
Description
Required. Specifies the first string to compare.
Required. Specifies the second string to be compared.
Required. Specifies the number of characters per string used for comparison.

    0 - If the two strings are equal
  • 77c4a490f1adeec2532be224228b060f0 - if string1 is greater than string2
  • ##Example:

<?php
echo strncasecmp("Hello world!","hello earth!",6);
?>
Output:

0

Recommended learning: "
PHP Video Tutorial

"

The above is the detailed content of How to compare strings in php (case insensitive). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn