PHP/String/substr count

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

Counting the Occurrences of a Substring

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



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

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



substr_count.php

 
<?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).<br />";
   }
?>



Testing for Substrings

 
<?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;
  }
?>