PHP/String/substr count

Материал из Web эксперт
Перейти к: навигация, поиск

Counting the Occurrences of a Substring

   <source lang="html4strict">

<?php $counter = substr_count ("Hello World!","o"); echo "There are " . $counter . " instance (s) of \"o\" in Hello World!."; ?>

 </source>
   
  


substr_count() function returns the number of times substring occurs in string.

   <source lang="html4strict">

Its syntax is: int substr_count (string string, string substring) <? $tng_twist = "The rain"; $count = substr_count($tng_twist, "ain"); print $count; ?>

 </source>
   
  


substr_count.php

   <source lang="html4strict">

<?php

  $buzzwords = array("this", "is", "test");

$talk = <<< talk this is a test. this is a test. this is a test. this is a test. this is a test. this is a test. this is a test. this is a test. this is a test. this is a test. this is a test. this is a test. this is a test. this is a test. this is a test. this is a test. this is a test. this is a test. talk;

  foreach($buzzwords as $bw) {
     echo "The word $bw appears ".substr_count($talk,$bw)." time(s).
"; }

?>

 </source>
   
  


Testing for Substrings

   <source lang="html4strict">

<?php

 $counter = substr_count ("Hello World!","o");
 echo "There are " . $counter . " instance (s) of \"o\" in Hello World!.";

?> <?php

 $theclientstext = "Hello, how are you today? I am fine!";
 if (strlen ($theclientstext) >= 30){
   echo substr ($theclientstext,0,29);
 } else {
   echo $theclientstext;
 }

?>

 </source>