如何在忽略大小写的情况下计算字符串中单词的出现次数

时间:2012-09-23 21:12:03

标签: php

我试图在忽略案例时计算给定单词的出现次数。 我试过了

<?php 
 $string = 'Hello World! EARTh in earth and EARth';//string to look into.
  if(stristr($string, 'eartH')) {
    echo 'Found';// this just show eartH was found.
  }
  $timesfound = substr_count($string, stristr($string, 'eartH'));// this count how many times. 

  echo $timesfound; // this outputs 1 instead of 3.

2 个答案:

答案 0 :(得分:4)

在搜索前小写字符串:

$string = 'Hello World! EARTh in earth and EARth';
$search = 'EArtH';
var_dump(substr_count(strtolower($string), strtolower($search))); // outputs 3

答案 1 :(得分:-1)

尝试substr_count()

     <?php
     $text = 'This is a test';
     echo strlen($text); // 14

    echo substr_count($text, 'is'); // 2

    ?>