2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【php】文字列の出現回数を調べる

Posted at

#substr_count()
文字列の出現回数を検索する ※大文字小文字を区別する

#文字列の出現数を調べる「substr_count()」

<?php
$text = 'This is a test';
echo substr_count($text, 'is').'<br/>';
// 実行結果 2
?>

###4文字目から検索

<?php
$text = 'This is a test';
// 文字列は 's is a test' になっているので, 1 が表示される
echo substr_count($text, 'is', 3).'<br/>';
?>

###4文字目から3文字検索

<?php
$text = 'This is a test';
// テキストは 's i' になっているので, 0 が表示される
echo substr_count($text, 'is', 3, 3).'<br/>';
?>

###6文字目から10文字検索

<?php
$text = 'This is a test';
// 5+10 > 14 なので、警告が発生する
echo substr_count($text, 'is', 5, 10).'<br/>';
//PHP Warning:  substr_count(): Invalid length value in
?>

###重なった場合

<?php
$text2 = 'ABBABBA';
// 重なっている副文字列はカウントされないので、1 が表示される
echo substr_count($text2, 'ABBA').'<br/>';
?>
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?