PHP preg_match(): 正規表現 (Regex)

⚡ スマートサマリー

Regular Expressions in PHP are pattern-matching tools that validate, split, and replace text in a single expression. This walkthrough covers the core functions preg_match, preg_split, and preg_replace, explains the common metacharacters, and builds a working email validation pattern step by step.

  • 🧩 What Regex Is: A regular expression is a pattern that describes text, letting one function validate, search, or transform strings.
  • preg_match: preg_match tests whether a pattern appears in a string and returns true on the first match, ideal for validation.
  • ✂️ preg_split: preg_split breaks a string into an array wherever the pattern occurs, such as splitting a sentence on spaces.
  • 🔁 preg_replace: preg_replace finds every match of a pattern and replaces it with new text, useful for templating and highlighting.
  • 🔤 メタキャラクター: Symbols like ., ^, $, *, and + build complex patterns, for example anchoring a match to the start or end.
  • 📧 Email Pattern: Character classes and quantifiers combine into a single pattern that checks whether an email address is well formed.
  • 🤖 AIアシスト: AI tools can write a regex from a plain description and explain or debug a complex existing pattern.

PHP Regular Expressions

What is Regular expression in PHP?

PHP regular expressions, also known as regex, are a powerful pattern matching tool that can be performed in a single expression. Regular expressions use special characters such as +, -, and ^ to create complex expressions. They can help you accomplish tasks such as validating email addresses, IP addresses, and more.

正規表現を使用する理由

  • PHP regular expressions simplify identifying patterns in string data by calling a single function. This saves us coding time.
  • When validating user input such as email addresses, domain names, telephone numbers, and IP addresses
  • 検索結果内のキーワードを強調表示する
  • カスタム HTML テンプレートを作成する場合。 PHP の正規表現を使用すると、テンプレート タグを識別し、実際のデータに置き換えることができます。

PHP の組み込み正規表現関数

PHP has built-in functions that allow us to work with regular expressions, which we will learn in this tutorial. Let us look at the commonly used regular expression functions in PHP.

  • preg_match() in PHP – this function is used to perform pattern matching on a string. It returns true if a match is found and false if a match is not found.
  • preg_split() in PHP – this function is used to perform a pattern match on a string and then split the results into a numeric array.
  • PHP の preg_replace() – この関数は、文字列に対してパターン マッチを実行し、一致したものを指定されたテキストに置き換えるのに使用されます。

Below is the syntax for a regular expression function such as preg_match(), preg_split(), or preg_replace().

<?php
function_name('/pattern/',subject);
?>

ここに、

  • “function_name(…)” is either preg_match(), preg_split(), or preg_replace().
  • “/…/” the forward slashes denote the beginning and end of our regular expression
  • “‘/pattern/'” is the pattern that we need to match
  • 「件名」は照合対象のテキスト文字列です。

Let us now look at practical examples that implement the above PHP regex functions.

PHP の Preg_match()

The first example uses the preg_match() function to perform a simple pattern match for the word guru in a given URL.

The code below shows the implementation of the preg_match() function for the above example.

<?php
$my_url = "www.guru99.com";
if (preg_match("/guru/", $my_url))
{
echo "the url $my_url contains guru";
}
else
{
echo "the url $my_url does not contain guru";
}
?>

を参照 URL http://localhost/phptuts/preg_match_simple.php

組み込みの正規表現関数

Let us examine the part of the code responsible for our output, preg_match(‘/guru/’, $my_url). HERE,

  • 「preg_match(…)」はPHPの正規表現関数です。
  • 「'/guru/'」は一致する正規表現パターンです
  • 「$my_url」は、照合するテキストを含む変数です。

PHP Preg_split()

Let us now look at another example that uses the preg_split() function.

文字列フレーズを取得し、それを配列に分解します。 一致するパターンは単一のスペースです。

この例で使用するテキスト文字列は「I Love Regular Expressions」です。

以下のコードは、上記の例の実装を示しています。

<?php

$my_text = "I Love Regular Expressions";

$my_array = preg_split("/ /", $my_text);

print_r($my_array );

?>

を参照 URL http://localhost/phptuts/preg_split.php

PHP Preg_split()

PHP Preg_replace()

Let us now look at the preg_replace() PHP関数 パターンの一致を実行し、パターンを別のものに置き換えます。

以下のコードは、「guru」という単語を検索します。 string.

It replaces the word guru with the word guru surrounded by CSS code that highlights the background color.

<?php

$text = "We at Guru99 strive to make quality education affordable to the masses. Guru99.com";

$text = preg_replace("/Guru/", '<span style="background:yellow">Guru</span>', $text);

echo $text;

?>

Assuming you have saved the file preg_replace.php, browse to the URL http://localhost/phptuts/preg_replace.php

PHP Preg_replace()

正規表現のメタ文字

The above examples used very basic patterns. Metacharacters allow us to perform more complex pattern matches, such as testing the validity of an email address. Let us now look at the commonly used metacharacters.

メタキャラクター 詳細説明 例:
. 改行を除く任意の XNUMX 文字と一致します /./ は XNUMX 文字を含むものに一致します
^ Matches the beginning of a string or excludes characters /^PH/ は、PH で始まる任意の文字列と一致します。
$ Matches a pattern at the end of the string /com$/ matches guru99.com, yahoo.com etc.
* Matches zero or more of the preceding characters /com*/ はコンピュータ、通信などに一致します。
+ Requires the preceding character(s) appear at least once /yah+oo/ は yahoo と一致します
\ Used to escape metacharacters /yahoo+\.com/ はドットをリテラル値として扱います
[...] キャラクタークラス /[abc]/ matches a, b or c
AZ 小文字と一致します /az/ は、cool、happy などに一致します。
AZ 大文字と一致します /AZ/ は、WHAT、HOW、WHY などに一致します。
0-9 0 から 9 までの任意の数値と一致します /0-4/ は 0,1,2,3,4、XNUMX、XNUMX、XNUMX、XNUMX に一致します

上記のリストには、正規表現で最も一般的に使用されるメタ文字のみが示されています。

Let us now look at a fairly complex example that checks the validity of an email address.

<?php
$my_email = "name@company.com";
if (preg_match("/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/", $my_email)) {
echo "$my_email is a valid email address";
}
else
{
echo "$my_email is NOT a valid email address";
}
?>

Explaining the Email Validation Pattern

ここに、

  • “/…/” starts and ends the regular expression
  • “^[a-zA-Z0-9._-]” matches any lower or upper case letters, numbers between 0 and 9, and dots, underscores, or dashes.
  • “+@[a-zA-Z0-9-]” matches the @ symbol followed by lower or upper case letters, numbers between 0 and 9, or dashes.
  • “+\.[a-zA-Z.]{2,5}$/” escapes the dot using the backslash, then matches any lower or upper case letters with a character length between 2 and 5 at the end of the string.

を参照 URL http://localhost/phptuts/preg_match.php

PHP Email Validation Pattern

As you can see from the above breakdown, metacharacters are very powerful when it comes to matching patterns.

よくあるご質問

preg_match stops at the first match and fills $matches with that one result. preg_match_all finds every match in the string and returns them all in a nested array, which suits extracting repeated items.

Modifiers follow the closing delimiter and change matching behavior. The i modifier makes the pattern case insensitive, m treats each line separately for ^ and $, and s lets the dot match newlines, as in /guru/i.

Wrap parts of the pattern in parentheses to create capture groups. After preg_match, the full match is in $matches[0] and each group follows in $matches[1], $matches[2], and so on.

Yes. Describe the text you want to match, such as a phone number or date format, and AI can produce the pattern plus a preg_match example. Test it against real and edge-case inputs before relying on it.

Yes. Paste the pattern, and AI can break it down token by token, explain what each part matches, and point out why it fails on certain input, then suggest a corrected version.