Archive

Posts Tagged ‘text’

Extract Keywords From A Text String With PHP

May 21st, 2009 1 comment

A common issue I have come across in the past is that I have a CMS system, or an old copy of WordPress, and I need to create a set of keywords to be used in the meta keywords field. To solve this I put together a simple function that runs through a string and picks out the most commonly used words in that list as an array. This is currently set to be 10, but you can change that quite easily.

The first thing the function defines is a list of "stop" words. This is a list of words that occur quite a bit in English text and would therefore interfere with the outcome of the function. The function also uses a variant of the slug function to remove any odd characters that might be in the text.

function commonWords($string){
    $stopWords = array('i','a','about','an','and','are','as','at','be','by','com','de','en','for','from','how','in','is','it','la','of','on','or','that','the','this','to','was','what','when','where','who','will','with','und','the','www');
 
    $string = preg_replace('/ss+/i', '', $string);
    $string = trim($string); // trim the string
    $string = preg_replace('/[^a-zA-Z0-9 -]/', '', $string); // only take alphanumerical characters, but keep the spaces and dashes too…
    $string = strtolower($string); // make it lowercase
 
    preg_match_all('/([a-z]*?)(?=s)/i', $string, $matchWords);
    $matchWords = $matchWords[0];
    foreach ( $matchWords as $key=>$item ) {
        if ( $item == '' || in_array(strtolower($item), $stopWords) || strlen($item) <= 3 ) {
            unset($matchWords[$key]);
        }
    }
    $wordCountArr = array();
    if ( is_array($matchWords) ) {
        foreach ( $matchWords as $key => $val ) {
            $val = strtolower($val);
            if ( isset($wordCountArr[$val]) ) {
                $wordCountArr[$val]++;
            } else {
                $wordCountArr[$val] = 1;
            }
        }
    }
    arsort($wordCountArr);
    $wordCountArr = array_slice($wordCountArr, 0, 10);
    return $wordCountArr;                
}

Here is an example of the function in action.

$text = "This is some text. This is some text. Vending Machines are great.";
$words = commonWords($text);
echo implode(',', array_keys($words));

This produces the following output.

some,text,machines,vending

Find Appropriate Colour In PHP

February 25th, 2009 No comments

Use the following function if you want to print the text in a particular colour, depending on what the background colour is.

function opposite($color) {
 $white = 0;
 for ($i = 0; $i < 6; $i += 2) {
  $white += base_convert(substr($color,$i,2),16,10) > 127 ? 1 : 0;
 }
 return $white >= 2 ? "000000" : "ffffff";
}

It works by looking at the colour and seeing how much of it is white. If greater than two parts are significantly white then the color returned is black, otherwise white is returned.

Here are some examples to test the function out.

echo '<span style="background-color:#ffffff;color:#'.opposite('ffffff').'">XXXXXX</span>';
echo '<span style="background-color:#000000;color:#'.opposite('000000').'">XXXXXX</span>';
echo '<span style="background-color:#fedbad;color:#'.opposite('fedbad').'">XXXXXX</span>';
echo '<span style="background-color:#123456;color:#'.opposite('123456').'">XXXXXX</span>';
echo '<span style="background-color:#fe13ef;color:#'.opposite('fe13ef').'">XXXXXX</span>';

Using JavaScript To Select Text

July 1st, 2008 No comments

This is a simple trick that will allow users to select the contents of a text area. First we need a text area.

<form><textarea name="textarea1" id="textarea1" rows="5" cols="40" wrap="off">This is some
long content.
This is some long content.
This is some long content.
This is some long content.
</textarea>
<br />
<input type="button" value="Select text" onclick="selectText('textarea1')">
</form>

This form also includes a button with an on click event that runs a function. This function takes a single parameter as the name of the element. It then sets the focus to this element and then selects all of the text therein.

function selectText(id){
 var id = document.getElementById(id);
 id.focus();
 id.select();
}

Why is this useful? Well lets say you had a form or a quiz that produced and answer, and you wanted people to post their answer on their blogs, which then linked back to your quiz. This would allow users to select the contents of a text area without having to select it themselves.

Categories: PHP Tags: , , , ,

PSPad – The Free Text Editor

April 30th, 2008 3 comments

Since starting programming I have used a lot of text editors, some have been good, and some have been very, very bad.

One text editor that stands out is PSPad. It is a free text editor for Windows that has lots of features and is very stable. I have been using this for a while now and have seen very little problems. I say "very little" as I once tried to open a 800 megabyte log file and it fell over, which is understandable.

PSPad

It has the following features:

  • Have many different files open with multi tabbed editing.
  • Close and re-open the editor with the same files you had open.
  • Built-in FTP client.
  • Search and replace in files.
  • A very neat text difference engine which highlights differences.
  • Create new files from templates in HTML, PHP, Pascal, JScript, VBScript, MySQL, MS-Dos, Perl and a few more.
  • Fully functional HEX editor.
  • Intelligent syntax highlighting dependent on file type, which can be changed to any other syntax highlighting.
  • Ability for users to create their own syntax highlighting.
  • Print out text with coloured syntax highlighting.
  • When typing you can press Ctrl and space to see a list of functions that start with what you have typed. This is an intelligent list so if you are writing in PHP you will be given a list of PHP functions.
  • Built in code explorer that allows you to view functions and classes in your files. Created for PHP, XML, HTML, INI, C/C++ and Pascal, but more are in development.
  • Spell checker.
  • Auto correction of code.
  • Bracket and tag matching.
  • HTML code tidying and formatting.
  • HTML entities and ASCII chart.
  • Text manipulation with line sorting, removing blank lines and regular expression text replacing.
  • Export text with syntax highlight to HTML, RTF, Tex format or to clipboard.
  • Ability to link program with external compilers and capture error messages.
  • Record, save and load macros to carry out repetitive tasks.
  • Create a project so keep track of multiple files.
  • Many more features besides these few.

Here is a screen shot.

PSPad Screenshot

Personally I find the bracket and tag matching extremely useful, and is a feature that makes it stand above professional text editors like Dreamweaver. If you are battling with your current text editor then give PSPad a go and see how easy it is.

Categories: Websites Tags: , , ,

Flashing JavaScript Text

January 27th, 2008 No comments

Here is a simple function that makes text in a tag fade into one colour slowly before quickly fading back into the original colour. If the background is the same colour as the text then the text will appear to fade in and out.

var color = 0;
var dir = 1;
function fade(){
  var quick = 50;
  var slow = 100;
  var el = document.getElementById('fadeInOut');
  if(!el){
    return;
  }
 
  if(dir){
    if (color < 255) {
      setTimeout(fade,slow);
      color += 10;
    }else{
      setTimeout(fade,quick);
      color = 255;
      dir = 0;
    }
  }else{
    if(color > 0){
      setTimeout(fade,quick);
      color -= 10;
    }else{
      setTimeout(fade,slow);
      color = 0;
      dir = 1;
    }
  }
  el.style.color = "rgb("+color+","+color+","+color+")";
}

This code works by using a group of setTimeout function calls to call the function in a loop. Each time the function is run some variables are set, the colour is changed and then the function is called again. Use it in the following way.

<body onload="fade();">
  <div id="fadeInOut" style="font-size:100px;">Fading Text</div>
</body>

So what would you use this for? Well if you where doing something intensive on a site you could use this trick to allow the user to see that things are going on before displaying the content that they requested.