文字列の検索と置換
strpos、str_replace、str_containsでテキストを検索・置換します。
「文字列の検索と置換」はCoddyKit上の無料PHP Academyレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはPHP Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 PHP Academyコースには全4レッスンが含まれています。
文字列内のテキストを検索する
PHPには部分文字列を検索する多くの関数があります。主な関数は次のとおりです:
strpos()— 最初に現れる位置を検索strrpos()— 最後に現れる位置を検索str_contains()— PHP 8で追加された、存在を確認する関数str_starts_with()/str_ends_with()— PHP 8で追加された関数
strpos()
最初に現れる位置(0始まり)を返します。見つからない場合はfalseを返します:
<?php
$str = 'the quick brown fox';
$pos = strpos($str, 'brown');
echo $pos; // 10
// Always use === to check for false (0 is also falsy!)
if (strpos($str, 'quick') !== false) {
echo 'Found!';
}str_contains、str_starts_with、str_ends_with
PHP 8では、これらの簡潔な真偽値ヘルパー関数が追加されました:
<?php
$email = 'user@example.com';
var_dump(str_contains($email, '@')); // true
var_dump(str_starts_with($email, 'user')); // true
var_dump(str_ends_with($email, '.com')); // true
var_dump(str_ends_with($email, '.org')); // falsestr_replace()
検索文字列に一致するすべての箇所を、置換文字列に置き換えます:
<?php
$template = 'Hello {name}, your order #{id} is ready.';
$result = str_replace(
['{name}', '{id}'],
['Alice', '4521'],
$template
);
echo $result;
// Hello Alice, your order #4521 is ready.str_ireplace() — 大文字・小文字を区別しない置換
str_ireplace()はstr_replace()と同様に動作しますが、大文字・小文字を区別しません:
<?php
$text = 'PHP is great. php is powerful. PHP is fun.';
$result = str_ireplace('php', 'PHP 8', $text);
echo $result;
// PHP 8 is great. PHP 8 is powerful. PHP 8 is fun.substr_replace()
位置と長さを指定して、文字列の一部を置き換えます:
<?php
$str = 'Hello World';
echo substr_replace($str, 'PHP', 6, 5);
// Hello PHP
// Replace from end
echo substr_replace($str, '!', -1);
// Hello Worl!substr_count()
部分文字列が何回現れるかを数えます:
<?php
$text = 'to be or not to be';
echo substr_count($text, 'be'); // 2
echo substr_count($text, 'to'); // 2
echo substr_count($text, 'or'); // 1preg_replace() — 正規表現による置換
複雑な置換には、正規表現パターンを使用します:
<?php
$html = '<p>Hello <b>World</b></p>';
// Strip HTML tags
$plain = preg_replace('/<[^>]+>/', '', $html);
echo $plain; // Hello World
// Replace multiple spaces with one
$spaced = 'too many spaces';
echo preg_replace('/\s+/', ' ', $spaced);
// too many spacesXSS防止のためのhtmlspecialchars
XSS攻撃を防ぐため、ユーザー入力をHTMLに出力する前に必ずエスケープします:
<?php
$userInput = '<script>alert("hacked")</script>';
// Dangerous:
echo $userInput; // executes script!
// Safe:
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
// <script>alert("hacked")</script>置換回数のカウント
str_replace()では、オプションの第4引数を使用して置換回数を取得できます:
<?php
$text = 'cat and cat and cat';
$count = 0;
$result = str_replace('cat', 'dog', $text, $count);
echo $result; // dog and dog and dog
echo $count; // 3文字列のパディング
フォーマットを整えるため、文字列を指定した長さまで埋めます:
<?php
echo str_pad('42', 8); // '42 ' (right-pad)
echo str_pad('42', 8, '0', STR_PAD_LEFT); // '000042'
echo str_pad('PHP', 7, '-', STR_PAD_BOTH); // '--PHP--'確認問題
文字列が指定したプレフィックスで始まるかどうかを確認する、PHP 8の関数はどれですか:
まとめ: 検索と置換
主な関数:
strpos/strrpos— 位置を検索(=== falseで確認)str_contains/starts_with/ends_with— PHP 8の真偽値ヘルパー関数str_replace/str_ireplace— 単純な置換preg_replace— 正規表現による置換htmlspecialchars— HTML出力用にエスケープ
よくある質問
「文字列の検索と置換」レッスンは無料ですか?
はい。「文字列の検索と置換」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、PHP Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 PHP Academyコースには全4レッスンが含まれています。
「文字列の検索と置換」で何を学びますか?
strpos、str_replace、str_containsでテキストを検索・置換します。 ブラウザで直接実行するハンズオンコードでPHP Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
PHP Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのPHP Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。
「文字列の検索と置換」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このPHP Academyレッスンでコードを書いて実行できますか?
はい。すべてのPHP Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- 文字列の基礎と連結
- 文字列の検索と置換
- 部分文字列とパディング関数
- 文字列の分割と結合