PHP は文字列を比較するときに大文字と小文字を区別しない

Sheeraz Gul 2023年6月20日
PHP は文字列を比較するときに大文字と小文字を区別しない

このチュートリアルでは、PHP で大文字と小文字の区別を無視する方法を示します。

PHP は文字列を比較するときに大文字と小文字を区別しない

2つの文字列を比較するときに、両方の文字列の大文字と小文字を区別する必要がある場合があります。 PHP には、大文字と小文字を区別せずに 2つの文字列を比較する組み込みメソッド strcasecmp() が用意されています。

strcasecmp() メソッドは 2つのパラメーターを取ります。 どちらも比較対象の文字列です。 このメソッドは次の値を返します。

  1. 2つの文字列が等しい場合、strcasecmp() は 0 を返します。
  2. strcasecmp() は、最初の文字列が 2 番目の文字列より小さい場合、<0 を返します。
  3. strcasecmp() は、最初の文字列が 2 番目の文字列より大きい場合、>0 を返します。

このメソッドは文字列のみを比較し、値を返します。 文字列の大文字と小文字の違いのみの場合は、常に 0 が返されます。

例を参照してください:

<?php
$String1 = "This is Delftstack.com";
$String2 = "This is Delftstack.com";

// Both the strings are equal in case
$Result=strcasecmp($String1, $String2);

echo "The result for two equal strings is: ".$Result."<br>";

$String1 = "this is delftstack.com";
$String2 = "THIS IS DELFTSTACK.COM";

// first string is lowercase than the second string
$Result=strcasecmp($String1, $String2);

echo "The result for first string lowercase and second string uppercase is : ".$Result."<br>";


$String1 = "THIS IS DELFTSTACK.COM";
$String2 = "this is delftstack.com";

// first string is uppercase, then the second string
$Result=strcasecmp($String1, $String2);

echo "The result for first string uppercse and second string lowercase is: ".$Result;
?>

上記のコードは、文字列の大文字と小文字の違いを無視して文字列を比較します。 出力を参照してください:

The result for two equal strings is: 0
The result for first string lowercase and second string uppercase is : 0
The result for first string uppercse and second string lowercase is: 0

メソッド strcasecmp() でわかるように、小文字、大文字、文の大文字のすべての文字列は同じです。 そのため、常に 0 を返します。文字列が単語または文字で等しくない例を試してみましょう:

<?php

$String1 = "delftstack.com";
$String2 = "THIS IS DELFTSTACK.COM";

// first string is lowercase, then the second string
$Result=strcasecmp($String1, $String2);

echo "The result for first string is lower then second string : ".$Result."<br>";


$String1 = "THIS IS DELFTSTACK.COM";
$String2 = "delftstack.com";

// First string is greater then second string
$Result=strcasecmp($String1, $String2);

echo "The result for first string is greater then second string: ".$Result;
?>

strcasecmp() メソッドは、負数または正数の数値を返します。 出力を参照してください:

The result for first string is lower then second string : -16
The result for first string is greater then second string: 16
著者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

関連記事 - PHP String