downloads | documentation | faq | getting help | mailing lists | reporting bugs | sites | links | my 
search for in the  
view the version of this page
Last updated: Thu, 21 Aug 2003

CI. String functions


These functions all manipulate strings in various ways. Some more specialized sections can be found in the regular expression and URL handling sections.

For information on how strings behave, especially with regard to usage of single quotes, double quotes, and escape sequences, see the Strings entry in the Types section of the manual.


No external libraries are needed to build this extension.


There is no installation needed to use these functions; they are part of the PHP core.

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.




CRYPT_MD5 integer




ENT_COMPAT (integer)

ENT_QUOTES (integer)

ENT_NOQUOTES (integer)

CHAR_MAX (integer)

LC_CTYPE (integer)

LC_NUMERIC (integer)

LC_TIME (integer)

LC_COLLATE (integer)

LC_MONETARY (integer)

LC_ALL (integer)

LC_MESSAGES (integer)

STR_PAD_LEFT (integer)

STR_PAD_RIGHT (integer)

STR_PAD_BOTH (integer)

See Also

For even more powerful string handling and manipulating functions take a look at the POSIX regular expression functions and the Perl compatible regular expression functions.

Table of Contents
addcslashes -- Quote string with slashes in a C style
addslashes -- Quote string with slashes
bin2hex --  Convert binary data into hexadecimal representation
chop -- Alias of rtrim()
chr -- Return a specific character
chunk_split -- Split a string into smaller chunks
convert_cyr_string --  Convert from one Cyrillic character set to another
count_chars --  Return information about characters used in a string
crc32 -- Calculates the crc32 polynomial of a string
crypt -- One-way string encryption (hashing)
echo -- Output one or more strings
explode -- Split a string by string
fprintf -- Write a formatted string to a stream
get_html_translation_table --  Returns the translation table used by htmlspecialchars() and htmlentities()
hebrev --  Convert logical Hebrew text to visual text
hebrevc --  Convert logical Hebrew text to visual text with newline conversion
html_entity_decode --  Convert all HTML entities to their applicable characters
htmlentities --  Convert all applicable characters to HTML entities
htmlspecialchars --  Convert special characters to HTML entities
implode -- Join array elements with a string
join -- Alias for implode()
levenshtein --  Calculate Levenshtein distance between two strings
localeconv -- Get numeric formatting information
ltrim --  Strip whitespace from the beginning of a string
md5_file -- Calculates the md5 hash of a given filename
md5 -- Calculate the md5 hash of a string
metaphone -- Calculate the metaphone key of a string
money_format -- Formats a number as a currency string
nl_langinfo --  Query language and locale information
nl2br --  Inserts HTML line breaks before all newlines in a string
number_format -- Format a number with grouped thousands
ord -- Return ASCII value of character
parse_str -- Parses the string into variables
print -- Output a string
printf -- Output a formatted string
quoted_printable_decode --  Convert a quoted-printable string to an 8 bit string
quotemeta -- Quote meta characters
rtrim --  Strip whitespace from the end of a string
setlocale -- Set locale information
sha1_file -- Calculate the sha1 hash of a file
sha1 -- Calculate the sha1 hash of a string
similar_text --  Calculate the similarity between two strings
soundex -- Calculate the soundex key of a string
sprintf -- Return a formatted string
sscanf --  Parses input from a string according to a format
str_ireplace --  Case-insensitive version of str_replace().
str_pad --  Pad a string to a certain length with another string
str_repeat -- Repeat a string
str_replace --  Replace all occurrences of the search string with the replacement string
str_rot13 -- Perform the rot13 transform on a string
str_shuffle -- Randomly shuffles a string
str_split --  Convert a string to an array
str_word_count --  Return information about words used in a string
strcasecmp --  Binary safe case-insensitive string comparison
strchr -- Alias for strstr()
strcmp -- Binary safe string comparison
strcoll -- Locale based string comparison
strcspn --  Find length of initial segment not matching mask
strip_tags -- Strip HTML and PHP tags from a string
stripcslashes --  Un-quote string quoted with addcslashes()
stripos --  Find position of first occurrence of a case-insensitive string
stripslashes --  Un-quote string quoted with addslashes()
stristr --  Case-insensitive strstr()
strlen -- Get string length
strnatcasecmp --  Case insensitive string comparisons using a "natural order" algorithm
strnatcmp --  String comparisons using a "natural order" algorithm
strncasecmp --  Binary safe case-insensitive string comparison of the first n characters
strncmp --  Binary safe string comparison of the first n characters
strpos --  Find position of first occurrence of a string
strrchr --  Find the last occurrence of a character in a string
strrev -- Reverse a string
strripos --  Find position of last occurrence of a case-insensitive string in a string
strrpos --  Find position of last occurrence of a char in a string
strspn --  Find length of initial segment matching mask
strstr -- Find first occurrence of a string
strtok -- Tokenize string
strtolower -- Make a string lowercase
strtoupper -- Make a string uppercase
strtr -- Translate certain characters
substr_count -- Count the number of substring occurrences
substr_replace -- Replace text within a portion of a string
substr -- Return part of a string
trim --  Strip whitespace from the beginning and end of a string
ucfirst -- Make a string's first character uppercase
ucwords --  Uppercase the first character of each word in a string
vprintf -- Output a formatted string
vsprintf -- Return a formatted string
wordwrap --  Wraps a string to a given number of characters using a string break character.

add a note add a note User Contributed Notes
String functions
thewolf at pixelcarnage dot com
23-Oct-2003 09:37
I got sick of trying to replace just a word, so I decided I would write my own string replacement code. When that code because far to big and a little faulty I decided to use a simple preg_replace:

    function word_replace($search, $replace, $subject) {
        Written by Rowan Lewis of
        $search(string), the string to be searched for
        $replace(string), the string to replace $search
        $subject(string), the string to be searched in
        return preg_replace('/[a-zA-Z]+/e', '\'\0\' == \'' . $search . '\' ? \'' . $replace . '\': \'\0\';', $subject);

I hope that this code helpes someone!
09-Oct-2003 04:41
Keep in mind when working with strings that some functions recognize the end of the strings by set of bytes HEX<0d0a> while others  recognize them only by one byte HEX<0d> . If you have HEX<0d> in the middle of the string such string will not be processed properly by some functions.
12-Aug-2003 10:16
Based on szeryf at negativeIQ dot pl's post on 02-Apr-2003 05:41, regarding truncating strings to the nearest whitespace.. I've come up with a slightly modified version.

The original version would stop at a newline and hence not output the specified number of characters.

function truncate ($var, $len = 120) {
    if (empty ($var)) { return ""; }
    if (strlen ($var) < $len) { return $var; }
    if (preg_match ("/(.{1,$len})\s./ms", $var, $match)) { return $match [1] . "..."; }
    else { return substr ($var, 0, $len) . "..."; }

The only difference is with the regular expression, from:

Hopefully this is helpful for someone other than myself. :-)
lille dot findus at telia dot com
18-Jul-2003 08:59
The first function to return 1st, 2nd etc was very ineffective, the second one don't work (try 21 for example).

Here's one that works(not too optimized though):

function nth($in)
    if(strlen($in)>1 && substr($in,-2,1)==1)
        return $in."th";
        case 1:
            return $in."st";
        case 2:
            return $in."nd";
        case 3:
            return $in."rd";
            return $in."th";
15-Jul-2003 10:51
Not long ago, i built a forum with PHP where HTML was allowed. One Problem than was, that some users used HTML but didn't close all tags, so the design of the page containing the entry was damaged. So I decided to make a function which closes all open Tags. It can also be used for closing tags of your own Code ([b] or so, as used in many boards)

function closeOpenTags($str, $open = "<", $close = ">", $end = "/", $tokens = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
{ $chars = array();
  for ($i = 0; $i < strlen($tokens); $i++)
  { $chars[] = substr($tokens, $i, 1); }

  $openedTags = array();
  $closedTags = array();
  $tag = FALSE;
  $closeTag = FALSE;
  $tagName = "";

  for ($i = 0; $i < strlen($str); $i++)
  { $char = substr($str, $i, 1);
    if ($char == $open)
    { $tag = TRUE; continue; }
    if ($char == $end)
    { $closeTag = TRUE; continue; }
    if ($tag && in_array($char, $chars))
    { $tagName .= $char; }
    { if ($closeTag)
      { if (isset($closedTags[$tagName]))
        { $closedTags[$tagName]++; }
        { $closedTags[$tagName] = 1; } }
      elseif ($tag)
      { if (isset($openedTags[$tagName]))
        { $openedTags[$tagName]++; }
        { $openedTags[$tagName] = 1; } }
      $tag = FALSE; $closeTag = FALSE; $tagName = ""; } }

  while(list($tag, $count) = each($openedTags))
  { $closedTags[$tag] = isset($closedTags[$tag]) ? $closedTags[$tag] : 0;
    $count -= $closedTags[$tag];
    if ($count < 1) continue;
    $str .= str_repeat($open.$end.$tag.$close, $count); }

  return $str; }

string closeOpenTags(string string [, string beginChar [, stringEndChar [, string CloseChar]]]);
MDonatas at centras dot lt
07-Jul-2003 07:21
I had to "translate" some project from ASP to PHP and found that in ASP there are some very useful string functions like:
string left ( string string, int length )
string right ( string string, int length )
string mid ( string string, int start [, int length] )

I think it's not hard to figure out what these functions do. If anyone finds it useful (I did), here is the code:

function left ($str, $howManyCharsFromLeft)
  return substr ($str, 0, $howManyCharsFromLeft);

function right ($str, $howManyCharsFromRight)
  $strLen = strlen ($str);
  return substr ($str, $strLen - $howManyCharsFromRight, $strLen);

function mid ($str, $start, $howManyCharsToRetrieve = 0)
  if ($howManyCharsToRetrieve === 0)
    $howManyCharsToRetrieve = strlen ($str) - $start;

  return substr ($str, $start, $howManyCharsToRetrieve);
yuelinniao at bbs dot nju dot edu dot cn
30-May-2003 05:32
I wrote this function to cut a mixed string(there are English words/numbers/Chinese characters in it) into short strings.
You know, a Chinese character is made up of two bits, if divide
the two bits, the Chinese character can not be recognized.
So I make a judgement before cutting.
Hope this will help someone.
words_cut($string, 0, 5);
function words_cut($string, $begin, $shortlength, $number=1)
        $length = strlen($string);
        if($length > $shortlength * $number)
                $end = $begin + $shortlength;
                $flag = 0;
                for($x=$begin; $x < $end; $x++)
                        if(ord($string[$x]) <= 127)
                $first_part = substr($string, 0, $end);
                $last_part = substr($string, $end);
                $newstring = $first_part. "\n" .$last_part;

                return words_cut($newstring, $end, $shortlength, $number);
                return $string;
szeryf at negativeIQ dot pl
02-Apr-2003 04:41
This is a little function I wrote for shortening strings to some arbitrary length. It may be useful if you want to display only headlines (or just a few starting sequences) of a larger text. The text is shortened to the last white space character before $len chars and an ellipsis (...) is added at the end. If no white space is found, the first $len chars (and ...) are returned. So the maximal length of returned value is always $len + 3. Here it goes:

function shorten ($var, $len = 120)
        if (empty ($var)) {
                return "";
        if (strlen ($var) < $len) {
                return $var;
        if (preg_match ("/(.{1,$len})\s/", $var, $match)) {
                return $match [1] . "...";
        else {
                return substr ($var, 0, $len) . "...";

It should be pretty self-explanatory. The regular expression matches up to $len chars followed by a white space char (\s). The match is "greedy", so it always tries to match "as many as possible".
missnglnk at missnglnk dot com
25-Mar-2003 01:35
Here's a better function to get the numerical thingy (1st, 2nd, 3rd, etc):

function nth ($n) {
   $rn = $n{strlen($n)};
   switch ($rn) { 
     case 1: $suffix = "st"; break; 
      case 2: $suffix = "nd"; break; 
     case 3: $suffix = "rd"; break; 
     default: $suffix = "th"; break; 
   return $n . $suffix;
kop at meme dot com
07-Mar-2003 08:49
function standardize_eol($s) {
  /* Return text with Unix end of line conventions.
   * Input: $s  The string to convert.
   * Returns: The string with Unix end of line conventions.
   * Side Effects: none
        return strtr(ereg_replace("\r\n", "\n", $s), "\r", "\n");

To do the same thing to a file:

// Copy file, converting
// Windoze and mac eol sequences to Unix eol along the way.
      exec("sed -e 's/\r\$//' $old_path"
           . ' | tr "\\r" "\\n"'
           . " > $new_path");

Do _not_ try to set $old_path and $new_path to the same file.  Failure will be erratic.
webmaster at gamequbed dot com
02-Feb-2003 07:14
I was recently working on a template engine, and i found that i wanted to add parameters to my template includes, for example,

{SUBJECTFIELD template="LINK_ROW" class="subjectfield"}

I found that this code worked out quite well! It converts the string into


which will print

"LINK_ROW". It also works for multiple blocks. Have fun!

$text = "
{SUBJECTFIELD class=\"alternate\" rowtemplate=\"LINK_ROW\"}
{BODYFIELD class=\"alternate2\" rowtemplate=\"LINK_ROW\"}";

## remove quotes
$text = str_replace("\"","",$text);

## set counter
$counter = 0;

for ($i=0;$i<strlen($text);$i++)
    ## convert each {...} block into an array element
    if ($text[$i] == "{")
        $currentEndBrace = strpos($text,"}");

        $param[$counter] = substr($text,$i,$currentEndBrace);

        ## remove the end brace
        $text[$currentEndBrace] = "";


$fileParam = array();

for ($j=0;$j<count($param);$j++)
    ## remove trailing stuff
    $param[$j] = rtrim($param[$j]);

    ## and the braces
    $param[$j] = ereg_replace("{","",$param[$j]);
    $param[$j] = ereg_replace("}","",$param[$j]);

    ## get the name of the template
    $tempIdent = substr($param[$j],0,strpos($param[$j]," "));

    ## get the rest of the vars
    $param[$j] = substr($param[$j],strpos($param[$j]," ")+1);

    ## make a new array
    $fileParam[$tempIdent] = $param[$j];

while(list($key,$val) = each($fileParam))
    ## set up as a query string
    $val = str_replace(" ","&",$val);

    ## parse it to a new array

    ## and assign it to another array
    $fileParam[$key] = $eachVal;
discord at mac dot com
24-Oct-2002 06:30
If you are outputting to html, it might be better to insert a wordbreak (<wbr>) tag to allow a linebreak. If the text is too long and needs to be wrapped, the browser will break the line at that tag, otherwise, it ignores it. This is good because it won't even show up as a space if the browser doesn't wrap it at that point.

Here's an optimised preg_replace version of the strmaxwordlen function that uses this tag:

function splitLongWords($text, $max) {
??return preg_replace( '/([^\s]{'.$max.'})(?=[^\s])/', '$1<wbr>', $text);

(note: I didn't test this thoroughly, it may need some work :)
d dot gebuehr at ntz dot de
13-Sep-2002 05:25
I've written a small function, which extracts all positions of a given character from a string. It may be useful for example to modify html-tags with not known values. (It's used to get rid of class-arguments and mso-styles while importing MS-Word-Documents):

function charpos($searchstring,$delimiter) {
global $positions;
global $search_found;
if (strpos($searchstring,$delimiter) === FALSE) {
else {
   for ($i_s=0;$i_s<$searchlen;$i_s++){if (substr($searchstring,$i_s,1)==$delimiter){$positions[]=$i_s; } }

You can work with the positions-array, but remember to unset it before calling the function again, otherwise you'll fill it more and more :-)
Counting of positions begins with 0. If the charakter you search for ist not to be found in your searchstring, the function returns $search_found=0, otherwise $search_found will be 1.
If typing the function, be sure to have three "=" in asking whether the charakter was found.
skip at seawana dot com
30-Aug-2002 05:24
// Here is a simpler way to swap two values (for alternating TABLE row colors for instance).
// Define your colors in an array:
$ar_colors = array ("#0066AA","#003399");

// Now simply display them and then reverse the array like this:
echo $ar_colors[0]; $ar_colors = array_reverse($ar_colors);
global2b at yahoo dot com
21-Aug-2002 11:25
In case any of you wanted to parse a deliminated text file, I've come up with a script that may of some use.

//I call the function and return the parsed data in a multi-D array.

function thisone() {
    $info = array();

//Here I take the first line of the data file and grab the variable names.
    $names = explode('|',$x[0]);

//Once I've got the variable names I delete x[0] so that I can run through the info array with foreach
    foreach($x as $keyx=>$valuex) {
        $w = explode('|',$valuex);
        foreach($w as $keyw=>$valuew) {
            $info[$keyx][$names[$keyw]] = $valuew;
    return $info;

$bin = thisone();
18-Jul-2002 11:02
How about reversing the HTML Chars (&eacute; => ?. Here is a function that is able to reverse any of HTML entitities regardles if the entity has the ";" termination. That means it can detect and replace "t&eacute;l&eacute;" => "t幨?, and also "t&eacutel&eacute" => "t幨?.

function ReverseHtmlChars ($str, $trans_table = HTML_ENTITIES) {

    $trans = get_html_translation_table ($trans_table);
    $trans2 = preg_replace ("';$'", "", $trans);
    $trans = array_flip ($trans);
    $trans2 = array_flip ($trans2);

    return strtr (strtr ($str, $trans), $trans2);

Also you can provide a second argument if you only want to replace the HTML specialchars.

I've read a note of the Editor in which he said that this is kinda pointless because normally you don't need to reverse HTML chars ... well, thats partially true.

In my case I really needes something like this because this way I can strip a html file of tags, reverse all HTML entities and obtain a very *human readable* text file !!! ... so its not so pointless.

P.S. you can also think of a similar function that has as second argument the translation table rather than 0/1 so you can have your own set of translations (very very useful for text translations)

dr dot helga at prickel-pit dot de
14-Jul-2002 09:41
For generating a Field-Number File I needed a function, wich can add chars in front or at the end of a string to match a certain string length. I couldn't find it in php so here's the function I wrote to solve the problem:

function addChars($string,$char,$endlength,$dir) {
    while ($i<$addchar_lenght) {
    if ($dir==1) {
    if ($dir==0) {
    return $new_string;

$string is the original string
$char is the character which shall be added
$endlength is the length of the new string
$dir specifies if the chars shall be added in front (0) or at the end (1) of the string

"1234" should be "00001234":


hope someone will find it usefull ...
chris at earleweb_nospam dot com
13-Jul-2002 04:03
An alternative to the the "array_shift" way to change $color array:

$Counter = 0; //set to 1 if you want to start on #CCCCCC
$Colors = Array('#FFFFFF', '#CCCCCC');
$tableColor = $Colors[($Counter %= 2)];
/* $Counter %= 2; ensures $Counter is never greater than 1, in the off chance that you have a 32 thousand element array and really is not needed -- you could use $Counter % 2 if you really want to*/

When ever $Counter is odd the modulus division will leave 1, but even numbers (and 0) mod 2 = 0.  Then Counter is added to so that the next phase of the loop will become the next color.
jewfish at jewfish dot net
06-Jun-2002 01:20
One could make an ever quicker isalphanumeric() function by using regular expressions:

function isalphanumeric($test) {
    return !(preg_match("/[^a-z,A-Z,0-9 ]/", $test));

Note: that is a space after the 9, in order to inclue spaces in the comparison.  One could also add \t and \n so that it did not fail out if it found a tab or newline.  This is much cleaner and more efficient than the array approach described earlier, and nicer than the ordinal characters approach as well.
captainbajoo at juno dot com
22-Apr-2002 07:09
This is a more compact function to get a numeric adjective.  No idea if it's faster than the other "nth" function here (though probably is, since "th" is more likely to occur), but the code is definitely shorter.

Assumes integer input.  Returns a string.

function getNth ($n) {
  $qn = (int) (($n%100) / 10);
  $rn = $n % 10;

  $suffix = "th";

  if ($qn != 1) {
    switch ($rn) {
    case 1: $suffix = "st"; break;
    case 2: $suffix = "nd"; break;
    case 3: $suffix = "rd"; break;

  return $n . $suffix;
carl at _nospam_youngbloods dot org
10-Jan-2002 12:27
I've ported a function to PHP that will find the longest common substring in two different strings.  Here it is:

function LongestCommonSubstring($string1, $string2)
    // find length of longest common substring first
    $L = array();
    $length1 = strlen($string1);
    $length2 = strlen($string2);
    for ($i = $length1; $i >= 0; $i--)
        for ($j = $length2; $j >= 0; $j--)
            if ($string1[$i] == '' || $string2[$j] == '') $L[$i][$j] = 0;
            elseif ($string1[$i] == $string2[$j]) $L[$i][$j] =
                   1 + $L[$i + 1][$j + 1];
            else $L[$i][$j] = max($L[$i + 1][$j], $L[$i][$j + 1]);

    // then find the actual substring
    $substring = '';
    $i = 0;
    $j = 0;
    while ($i < $length1 && $j < $length2)
        if ($string1[$i] == $string2[$j])
            $substring .= $string1[$i];
            $i++; $j++;
        elseif ($L[$i + 1][$j] >= $L[$i][$j + 1]) $i++;
        else $j++;
    return $substring;

Here is where I found the original:
rs234 at cornell dot edu
04-Aug-2001 07:31
there's a problem when i used the addslashes function for my odbc connection... in order to fix it, I used the htmlspecialchars($str_var, ENT_QUOTES); instead and it worked fine.  example is as follow:

// $str - a string w/ single quotes
$str = htmlspecialchars($str, ENT_QUOTES);
$sql = "<something> $str <something>";
thanatos at wol dot be
16-Jun-2001 05:45
I have written an *evil* little function that will cut a string on a character given. Features:
1) Minimum length.
2) If a string doesn't contain the character, it cuts your string to minimum length.
3) If the next character beyond the minimumlength equals the given character, it will cut the string to minimulength as well.

function cuttext($tring,$cuton) {

/* Define the character to cut on */
/* One could make an array with all characters to cut on */
/* But I wouldn't know how to :) */

$space=" ";

if (!
strstr($tring,$space)) {

/* No space is found in the whole string: cut at 20th character */
if (
substr($tring,$cuton,1)==$space) {

/* 21st character is a space: cut at 20th character */
} else {

/* 21st Character is NOT a space: return to last space and cut there */
while ($teller <= $cuton) {
        if (
substr($tring,$cuton-$teller,1)==$space) {
cuttext("waf groink muha zz gruu wrrreea iii gargghhh >:)>:)",20));
david at audiogalaxy dot com
14-Jun-2001 03:31
Browsers (Internet Explorer at least) won't wrap text immediately before puntuation . ? ! ( ) [ ] { } / even if the preceeding character is whitespace.  I believe this is intentional widow/orphan prevention behavior.  This complicates the processing of user-inputed text (e.g. the message board junk problem).  Even if you use <textarea wrap=hard> to force newlines into the input text (which is imperfect since a clever user can just modify the HTML before posting), people posting long strings of punctuation characters, or just punctuation characters at the beginning of each line in the <textarea> will mess up the format of the page for users viewing their post.

You obviously can't solve this by just inserting a spaces - the browser still won't wrap.  My solution is to use str_replace to put a &nbsp; (the least visually impacting non-whitespace character I can think of) between the \n and any pucntuation so the wrap can happen in the whitespace before the &nbsp;.  Kindof ironic to be using &nbsp; to *cause* a break:)

[Editor's note:

You could also use wordwrap() function

Maxim Maletsky]
R dot J dot Vrijhof at bigfoot dot com
26-Dec-2000 12:20
I wanted to convert numbers to an adjective form (so from "1" to "1st", from "352" to "352nd", etc.), but couldn't find it in PHP, so I wrote this little code to do that for me. Hope you find it useful:

function nth($in) {
  if (!is_long($in))
  switch ($in) {
    case 0 : return("0th");
    case 1 : return("1st");
    case 2 : return("2nd");
    case 3 : return("3rd");
    case 4 :
    case 5 :
    case 6 :
    case 7 :
    case 8 :
    case 9 :
    case 10 :
    case 11 :
    case 12 :
    case 13 :
    case 14 :
    case 15 :
    case 16 :
    case 17 :
    case 18 :
    case 19 : return($in."th");
  switch (substr($in, -1, 1)) {
    case 0 : return($in."th");
    case 1 : return($in."st");
    case 2 : return($in."nd");
    case 3 : return($in."rd");
    case 4 :
    case 5 :
    case 6 :
    case 7 :
    case 8 :
    case 9 : return($in."th");
    default : return(0);

It will return -1 when the input is not an integer and 0 when it couldn't find a match (although that shouldn't happen).
ognio at peruserver dot com
21-Sep-2000 08:39
In order to properly display text from a form into an html page you need code
like this:

<? echo htmlentities(stripslashes($_GET['form_text'])); ?>
mfawcett at tir dot com
25-Apr-2000 02:45
For a MySQL problem (where a user might put quotes in a text field from a form) use addslashes() to escape all quotes (single and double).  For example:

// Assuming 'textstuff' is from a form
$mytextstuff = addslashes($textstuff);
$sql = "insert into MyTable set MyField='$mytextstuff'";

Also if you are working with html forms and/or text fields from databases a lot you'll probably want to read up on commands like htmlspecialchars() as well (a field like "foo<bar>" might not throw MySQL off but it won't display correctly in an html page).
heiko at individual-web dot com
08-Mar-2000 12:24
I had the problem that in some of the guestbooks I programmed, people entererd trash like 400 characters without spaces and such.  Without any spaces there was no way to break the lines and the whole guestbooked looked screwed.  I wrote this little function that makes sure no words are more than a specified number of characters long.  If a word is too long, spaces are inserted to get the word to the maximum length allowed. Maybe it's useful to some of you:

function strmaxwordlen($input,$len) {
 $l = 0;
 $output = "";
 for ($i = 0; $i < strlen($input); $i++) {
  $char = substr($input,$i,1);
  if ($char != " ") { $l++; } else { $l = 0; }
  if ($l == $len) { $l = 0; $output .= " "; }
  $output .= $char;

[Editor's note:

Alternativaly, wordwrap() function is available for this purpose


 Last updated: Thu, 21 Aug 2003
show source | credits | sitemap | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by:
Last updated: Sat 01 Nov 2003 04:13:36 EST EST