Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Pspell Functions

Pspell Functions

Introduction

These functions allow you to check the spelling of a word and offer suggestions.

Requirements

To compile PHP with pspell support, you need the aspell library, available from » http://aspell.sourceforge.net/.

Installation

If you have the libraries needed add the --with-pspell[=dir] option when compiling PHP.

Note to Win32 Users:

In order for this extension to work, there are DLL files that must be available to the Windows system PATH. See the FAQ titled "How do I add my PHP directory to the PATH on Windows" for information on how to do this. Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the systems PATH), it is not recommended. This extension requires the following files to be in the PATH: aspell-15.dll from the bin folder of the aspell installation.

Win32 support is available only in PHP 4.3.3 and later versions. Also, at least aspell version 0.50 is required.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

This extension has no resource types defined.

Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

PSPELL_FAST (integer)
PSPELL_NORMAL (integer)
PSPELL_BAD_SPELLERS (integer)
PSPELL_RUN_TOGETHER (integer)

Table of Contents

pspell_add_to_personal — Add the word to a personal wordlist
pspell_add_to_session — Add the word to the wordlist in the current session
pspell_check — Check a word
pspell_clear_session — Clear the current session
pspell_config_create — Create a config used to open a dictionary
pspell_config_data_dir — location of language data files
pspell_config_dict_dir — Location of the main word list
pspell_config_ignore — Ignore words less than N characters long
pspell_config_mode — Change the mode number of suggestions returned
pspell_config_personal — Set a file that contains personal wordlist
pspell_config_repl — Set a file that contains replacement pairs
pspell_config_runtogether — Consider run-together words as valid compounds
pspell_config_save_repl — Determine whether to save a replacement pairs list along with the wordlist
pspell_new_config — Load a new dictionary with settings based on a given config
pspell_new_personal — Load a new dictionary with personal wordlist
pspell_new — Load a new dictionary
pspell_save_wordlist — Save the personal wordlist to a file
pspell_store_replacement — Store a replacement pair for a word
pspell_suggest — Suggest spellings of a word

Code Examples / Notes » ref.pspell

fragment

To get round the error on Windows where the word list can't be found inside functions, take the call to pspell_new() out of the function and pass the return value to your function, i.e.
<?
function testSpell($pspell_link) {
echo pspell_check($pspell_link, "test") ? 'OK' : 'Not OK';
}
$pspell_link = pspell_new("en");
testSpell($pspell_link);
?>


alan dunsmuir
There appears to be a problem currently affecting PSpell functionality on Windows machines.
Currently, the compiled build of PHP5 for Windows does not by default include PSpell, and to activate these functions the Windows user has to (a) install GNU ASpell; (b) copy the file aspell-15.dll to a directory in the Windows "Path" statement (typically C:\Windows\System32); (c) install one or more ASpell dictionaries; (d) enable the PSpell extension to PHP by adding a reference to php_pspell.dll in the php.ini file, and moving the file itself to the main PHP directory.
However, when this has all been done and PSpell appears to have been fully activated, there remains a problem. While all the PSpell functions work as specified when referenced from the "main" body of PHP code, if they are placed within a PHP function, the system reports that it is unable to find any word lists for the specified dictionary (whichever one is chosen).
I have a sample of PSpell-using code (taken from the SAMS book PHP 5 In Practice) which works perfectly on a Unix-based Web Server, but which fails with the indicated error message on a range of Windows machines.


dylan

preg_replace_callback() is the best way I found to check words in a large text and change the HTML color of words that are not found.  Here is a script I wrote which does just that, and optionally uses pspell_suggest() to auto-correct. I would love to write a better regex to ignore <text inside xml tags>, but that really isn't as easy as it sounds...
<?php
$pspell = pspell_new('en','canadian','','utf-8',PSPELL_FAST);
function spellCheckWord($word) {
global $pspell;
$autocorrect = TRUE;
// Take the string match from preg_replace_callback's array
$word = $word[0];

// Ignore ALL CAPS
if (preg_match('/^[A-Z]*$/',$word)) return $word;
// Return dictionary words
if (pspell_check($pspell,$word))
return $word;
// Auto-correct with the first suggestion, color green
if ($autocorrect && $suggestions = pspell_suggest($pspell,$word))
return '<span style="color:#00FF00;">'.current($suggestions).'</span>';

// No suggestions, color red
return '<span style="color:#FF0000;">'.$word.'</span>';
}
function spellCheck($string) {
return preg_replace_callback('/\b\w+\b/','spellCheckWord',$string);
}
echo spellCheck('PHP is a reflecktive proegramming langwage origenaly dezigned for prodewcing dinamic waieb pagges.');
?>
OUTPUT: PHP is a reflective programming language originally designed for producing dynamic Web pages.


tidd

In response to csnyder's comment about calling aspell instead of using the aspell or pspell libs:
If you are running a low traffic site this will work fine and it's a good idea.
If, however, you have many customers using your spell checking script, this method does not scale well and you should consider spending the time to make the libs work properly.


andrew

If you use red hat or fedora, you may need to is use
 yum install pspell-devel  
(fixes: configure: error: Cannot find pspell)


gregory boshoff

If you are receiving the error message:
PSPELL couldn't open the dictionary. reason:
No word lists can be found for the language "en".
Add following lines prior to calling pspell_check:
$pspell_config = pspell_config_create("en");
$pspell_link = pspell_new_config($pspell_config);


jrweir _a_t_ yahoo

I had the same problems after following the detailed instructions for installing on windows but was able to solve them by doing the following:
first, I copied all the files in the data directory of the aspell install (ie. C:\Program Files\Aspell\data) to a unix machine and ran dos2unix on all of the files and then copied them back.
second, added this line before the pspell_new("en") call
pspell_config_create("en");
hope this works for you too.


beau_scott

hehe, forgot to remove the echo $string line... whoops ;)
Should be:
<?
/**
* Checks spelling of $string. Whole phrases can be sent in, too, and each word will be checked.
* Returns an associative array of mispellings and their suggested spellings
* @param string $string Phrase to be checked
* @return array
*/
function checkSpelling ( $string )
{
// Make word list based word boundries
$wordlist = preg_split('/\s/',$string);
// Filter words
$words = array();
for($i = 0; $i < count($wordlist); $i++)
{
$word = trim($wordlist[$i]);
if(!preg_match('/[A-Za-z]/', $word))
continue;
$word = preg_replace('/[^\w\']*(.+)/', '\1', $word);
$word = preg_replace('/([^\W]*)[^\w\']*$/', '\1', $word);
$word = trim($word);
if(!in_array($word, $words, true))
$words[] = $word;
}
$misspelled = $return = array();
$int = pspell_new('en');
foreach ($words as $value)
if (!pspell_check($int, $value))
$misspelled[] = $value;
foreach ($misspelled as $value)
$return[$value] = pspell_suggest($int, $value);
return $return;
}
?>


flint

For those will problems installing on Win32 with IIS:
Symptom: browser just hangs when calling pspell function. Running PHP.exe from command line causes pspell to claim that there is a corrupt file. Running Aspell works just fine on the command line.
You need new data files:
You can download and get more information about it here:
http://wiki.wordpress.org/SpellCheck
Just replace the data directory in C:\Programs Files\Aspell\ with the new data directory you downloaded.
No more problems.


10-dec-2004 09:52

For those of us in the Windows world, here is a great link on how to enable pspell for PHP on Win32:
http://www.oblius.com/?.blogs.184


webmaster

Easy way to make a spellchecker:
<?
function spellcheck ( $string ) {
$words = preg_split('/[\W]+?/',$string);
$misspelled = $return = array();
$int = pspell_new('en');
foreach ($words as $value) {
if (!pspell_check($int, $value)) {
$misspelled[] = $value;
}
}
foreach ($misspelled as $value) {
$return[$value] = pspell_suggest($int, $value);
}
return $return;
}
?>


jeremy hepler

compiling php with pspell on debian sarge:
apt-get install aspell libaspell15 libaspell-dev libpspell-dev
configure php:
./configure <your other options> --with-pspell=/usr
make & install
if previous tries have failed or it is not functioning properly, unpack the php source again and configure / compile in a fresh tree


sholland

Back in 10/2002 csnyder at chxo dot com wrote the first comment about the spell functions, and wrote a very sophisticated spell check with a direct call to aspell.  In a similar vein, I wrote a simplified a PHP function that will spell check a string and insert tags before and after the misspelled words. Auto-correction is not offered.
<?
function spellcheck($string) {
// Entry: $string: Text to spellcheck.
// Returns: string with '<strong>' and '</strong>' inserted before and
// after misspellings.

$pre='<strong>'; // Inserted before each mis-spelling.
$post='</strong>'; // Inserted after each mis-spelling.
$string=strtr($string,"\n"," ");
// Drop newlines in string. (It bothers aspell in this context.)
$mistakes = `echo $string | /usr/local/bin/aspell list`;
// Get list or errors.
$offset=0;
foreach (explode("\n",$mistakes) as $word)
// Walk list, inserting $pre and $post strings.  I move along and
// do the insertions, keeping track of the location.  A global replace
// with str_replace($string,$pre.$work.$post) is problematic if the
// same misspelling is found more than once.
if ($word<>"") {
$offset=strpos($string,$word,$offset);
$string=substr_replace($string, $post, $offset+strlen($word), 0);
$string=substr_replace($string, $pre, $offset, 0);
$offset=$offset+strlen($word)+strlen("$pre $post");
};
return $string;};
?>
For this to work on your system, see if /usr/local/bin/aspell list runs from the shell.  It needs to get input from standard input.  You may not be able to run apell without the path for PHP because the PATH variable may be different in the PHP invocation from a shell invocation.


kevina

Aspell Author Here.
Since Aspell 0.50, Pspell is no longer used.  It is not necessary to download and install the Pspell package, only Aspell 0.50 (or better) is required.  Aspell now provided a backwards compatibility interface for programs expecting the old Pspell interface (such as PHP).
Even though Aspell now provided a new "Aspell" interface this, the PHP Pspell interface is the one you want to use.  The Aspell PHP interface is the one used with a *very* old version of Aspell as the manual says.
Sorry if this is confusing, but it is not really my fought as I have no control over PHP development.  Eventually a new Aspell interface should be provided for PHP which uses the new Aspell interface provided with Aspell 0.50 but for now the Pspell interface will work just fine.
Note: If you wish to use an older version of Aspell (_before_ 0.50) than both Aspell and Pspell are required.


csnyder

As an alternative to mucking about with the compiled-in aspell/pspell functions, which only check word by word, one could write a script that calls aspell as a shell exec to check a whole block of text:
http://chxo.com/scripts/spellcheck.php
(there is a view-source option)
Not sure about Linux or Windows, but installing aspell on FreeBSD was trivially easy from the ports collection. No doubt such a script could be easily modified to use ispell instead if you'd rather.


abhishek dot ratani

http://www.zend.com/zend/spotlight/spellchecking.php#Heading2
Great tutorial on spell checking. Check it out!


Change Language


Follow Navioo On Twitter
.NET Functions
Apache-specific Functions
Alternative PHP Cache
Advanced PHP debugger
Array Functions
Aspell functions [deprecated]
BBCode Functions
BCMath Arbitrary Precision Mathematics Functions
PHP bytecode Compiler
Bzip2 Compression Functions
Calendar Functions
CCVS API Functions [deprecated]
Class/Object Functions
Classkit Functions
ClibPDF Functions [deprecated]
COM and .Net (Windows)
Crack Functions
Character Type Functions
CURL
Cybercash Payment Functions
Credit Mutuel CyberMUT functions
Cyrus IMAP administration Functions
Date and Time Functions
DB++ Functions
Database (dbm-style) Abstraction Layer Functions
dBase Functions
DBM Functions [deprecated]
dbx Functions
Direct IO Functions
Directory Functions
DOM Functions
DOM XML Functions
enchant Functions
Error Handling and Logging Functions
Exif Functions
Expect Functions
File Alteration Monitor Functions
Forms Data Format Functions
Fileinfo Functions
filePro Functions
Filesystem Functions
Filter Functions
Firebird/InterBase Functions
Firebird/Interbase Functions (PDO_FIREBIRD)
FriBiDi Functions
FrontBase Functions
FTP Functions
Function Handling Functions
GeoIP Functions
Gettext Functions
GMP Functions
gnupg Functions
Net_Gopher
Haru PDF Functions
hash Functions
HTTP
Hyperwave Functions
Hyperwave API Functions
i18n Functions
IBM Functions (PDO_IBM)
IBM DB2
iconv Functions
ID3 Functions
IIS Administration Functions
Image Functions
Imagick Image Library
IMAP
Informix Functions
Informix Functions (PDO_INFORMIX)
Ingres II Functions
IRC Gateway Functions
PHP / Java Integration
JSON Functions
KADM5
LDAP Functions
libxml Functions
Lotus Notes Functions
LZF Functions
Mail Functions
Mailparse Functions
Mathematical Functions
MaxDB PHP Extension
MCAL Functions
Mcrypt Encryption Functions
MCVE (Monetra) Payment Functions
Memcache Functions
Mhash Functions
Mimetype Functions
Ming functions for Flash
Miscellaneous Functions
mnoGoSearch Functions
Microsoft SQL Server Functions
Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Mohawk Software Session Handler Functions
mSQL Functions
Multibyte String Functions
muscat Functions
MySQL Functions
MySQL Functions (PDO_MYSQL)
MySQL Improved Extension
Ncurses Terminal Screen Control Functions
Network Functions
Newt Functions
NSAPI-specific Functions
Object Aggregation/Composition Functions
Object property and method call overloading
Oracle Functions
ODBC Functions (Unified)
ODBC and DB2 Functions (PDO_ODBC)
oggvorbis
OpenAL Audio Bindings
OpenSSL Functions
Oracle Functions [deprecated]
Oracle Functions (PDO_OCI)
Output Control Functions
Ovrimos SQL Functions
Paradox File Access
Parsekit Functions
Process Control Functions
Regular Expression Functions (Perl-Compatible)
PDF Functions
PDO Functions
Phar archive stream and classes
PHP Options&Information
POSIX Functions
Regular Expression Functions (POSIX Extended)
PostgreSQL Functions
PostgreSQL Functions (PDO_PGSQL)
Printer Functions
Program Execution Functions
PostScript document creation
Pspell Functions
qtdom Functions
Radius
Rar Functions
GNU Readline
GNU Recode Functions
RPM Header Reading Functions
runkit Functions
SAM - Simple Asynchronous Messaging
Satellite CORBA client extension [deprecated]
SCA Functions
SDO Functions
SDO XML Data Access Service Functions
SDO Relational Data Access Service Functions
Semaphore
SESAM Database Functions
PostgreSQL Session Save Handler
Session Handling Functions
Shared Memory Functions
SimpleXML functions
SNMP Functions
SOAP Functions
Socket Functions
Standard PHP Library (SPL) Functions
SQLite Functions
SQLite Functions (PDO_SQLITE)
Secure Shell2 Functions
Statistics Functions
Stream Functions
String Functions
Subversion Functions
Shockwave Flash Functions
Swish Functions
Sybase Functions
TCP Wrappers Functions
Tidy Functions
Tokenizer Functions
Unicode Functions
URL Functions
Variable Handling Functions
Verisign Payflow Pro Functions
vpopmail Functions
W32api Functions
WDDX Functions
win32ps Functions
win32service Functions
xattr Functions
xdiff Functions
XML Parser Functions
XML-RPC Functions
XMLReader functions
XMLWriter Functions
XSL functions
XSLT Functions
YAZ Functions
YP/NIS Functions
Zip File Functions
Zlib Compression Functions
eXTReMe Tracker