Category Archives: Code

PHP – Determining the Frequency of a String’s Appearance

The substr_count() function returns the number of times one string occurs within another. Its prototype follows:


int substr_count(string str, string substring)

The following example determines the number of times an IT consultant uses various buzzwords in his presentation:

<?php
$buzzwords = array("mindshare", "synergy", "space");

$talk = "I'm certain that we could dominate mindshare in this space with
our new product, establishing a true synergy between the marketing
and product development teams. We'll own this space in three months.";

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

This returns the following:

——————————————–
The word mindshare appears 1 time(s).
The word synergy appears 1 time(s).
The word space appears 2 time(s).
——————————————–

Read more »

PHP – Split text up into 140 char array for Twitter

As you probably know, Twitter only accepts messages of 140 characters or less. If you want to interact with the popular social messaging site, you’ll enjoy this function for sure, which will allow you to truncate your message to 140 characters.

function split_to_chunks($to,$text){
$total_length = (140 - strlen($to));
$text_arr = explode(" ",$text);
$i=0;
$message[0]="";
foreach ($text_arr as $word){
if ( strlen($message[$i] . $word . ' ') >= $total_length ){
          if ($text_arr[count($text_arr)-1] == $word){
$message[$i] .= $word;
} else {
$message[$i] .= $word . ' ';
}
} else {
$i++;
if ($text_arr[count($text_arr)-1] == $word){
$message[$i] = $word;
} else {
$message[$i] = $word . ' ';
}
}
}
return $message;
}

WordPress – Dynamic Highlight Menu

This allows you to theme/style and control the currently selected menu tab in CSS by adding a class=”current” on it.

<ul id="nav">
  <li<?php if ( is_home() || is_category() || is_archive() || is_search() || is_single() || is_date() ) { echo ' class="current"'; } ?>><a href="#">Gallery</a></li>
  <li<?php if ( is_page('about') ) { echo ' class="current"'; } ?>><a href="#">About</a></li>
  <li<?php if ( is_page('submit') ) { echo ' class="current"'; } ?>><a href="#">Submit</a></li>
</ul>

Line 2:

If Home, or Category, or Archive, or Search or Single page is selected, class=”current” will be included in

  • Line 3,4:

    If Page with page slug about or submit is highlighted, class=”current” is added.

    If you are looking at putting categories as menu tabs, here’s how to make the menu dynamic:

    <ul id="nav">
      <li<?php if ( is_category('css') ) { echo ' class="current"'; } ?>><a href="#">CSS</a></li>
      <li<?php if ( is_category(showcase) ) { echo ' class="current"'; } ?>><a href="#">Showcase</a></li>
    </ul>
    

    If category with category slug of css or showcase, class=”current” is added.