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



PHP : Function Reference : String Functions

String Functions

Introduction

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.

Requirements

No external libraries are needed to build this extension.

Installation

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_SALT_LENGTH integer
CRYPT_STD_DES integer
CRYPT_EXT_DES integer
CRYPT_MD5 integer
CRYPT_BLOWFISH integer
HTML_SPECIALCHARS (integer)
HTML_ENTITIES (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
convert_uudecode — Decode a uuencoded string
convert_uuencode — Uuencode a string
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_decode — Convert special HTML entities back to characters
htmlspecialchars — Convert special characters to HTML entities
implode — Join array elements with a string
join — Alias of implode()
levenshtein — Calculate Levenshtein distance between two strings
localeconv — Get numeric formatting information
ltrim — Strip whitespace (or other characters) from the beginning of a string
md5_file — Calculates the md5 hash of a given file
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 (or other characters) 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_getcsv — Parse a CSV string into an array
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 of 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
strpbrk — Search a string for any of a set of 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_compare — Binary safe comparison of 2 strings from an offset, up to length 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 (or other characters) 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
vfprintf — Write a formatted string to a stream
vprintf — Output a formatted string
vsprintf — Return a formatted string
wordwrap — Wraps a string to a given number of characters

Code Examples / Notes » ref.strings

bloopletech

[Editor's Note: Remember that number names are locale-specific. Thus in the US 1,000,000,000 is called a billion, while in other countries this might be different (ie. miljard in Dutch). This function provides support only for the US locale]
If you want to convert a number, (int or float) to full spoken text, then you can use my num2text converter, at http://bloople.net/num2text
Examples:
40000 => forty thousand
1,796,706 => one million, seven hundred and ninety-six thousand, seven hundred and six.
If works for positive an negative integers/floats/doubles. The code is only a page long, and you don't have to install any modules or anything.
I hope this comes in handy for somebody!


beggining pro

Well for you egold users out ther I wrote this to just return the balance ONLY
If anyone knows a better way to write this lemme know as im a novice
function _GetBalance($from, $frompass) {
  $defined_vars = get_defined_vars();
  $_url = 'https://www.e-gold.com/acct/balance.asp';
$_url_p = "AccountID=" . $from . "&PassPhrase=" . $frompass ."";
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_POST,1);
  curl_setopt($ch, CURLOPT_POSTFIELDS,$_url_p);
  curl_setopt($ch, CURLOPT_URL,$_url);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);
  curl_setopt($ch, CURLOPT_USERAGENT, $defined_vars['HTTP_USER_AGENT']);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  $content = curl_exec ($ch);
  curl_close ($ch);
$content=strtolower($content);
$content=strstr($content,"</select></font></th></form></tr>");
$content=strip_tags($content);
$content=strrev($content);
$content=strstr($content,"eseht :eton");
$content=str_replace("eseht :eton","",$content);
$content=ltrim($content);
$content=rtrim($content);
$content=substr($content,0,11);
$content=strrev($content);
$content=ltrim($content);
  return $content;
}


14-oct-2005 04:24

Updated; used to test for input as an array, should have been a string, added some validation of the input while I was at it.  Enjoy.
<?php
/*----------        Directory Tree to Array        ----------//
 Takes base directory, returns an associative array
      containing each directory name as an associative key
      and each file as an indexed entry in the appropriate
      directory.
 If no path is provided, it uses the current directory
 If $style == 1, it will return a sorted, non-associative
      array
 By Peter Dolan
 www.peterd.net
 Updated 2005-10-12
 Use it as much as you like for whatever
 For my own entertainment, please let me know if you do
//-----------------------------------------------------------*/
function dirTreeToArray( $path = "./", $style="0" ) {
    if ( !is_string($path) or !($style==0 or $style==1) ) die("Improper arguments in function dirTreeToArray(string \$path, \$style = {0, 1})");
    else {
       $path = trim($path);
       $path = str_replace("\\", "/", $path);
       if( '/' == $path{strlen($path)-1} || '\'' == $path{strlen($path)-1} ) $path = substr($path, 0, strlen($path)-1);
    }
    $tree = array();
    $arrayPointer = & $tree;
  if ( $handle = opendir($path) ) {
      while ( $fileName = readdir($handle) ) {
            if ( $fileName != "." and $fileName != ".." ) {
                      $newPath = "$path/$fileName";        // Used for testing directory or file property
                if ( is_dir($newPath) ) {
                  $dummyPointer = & $arrayPointer;        // Save the current pointer
                    if ( $style == 0 ) $arrayPointer = & $arrayPointer[$fileName];    // Drop the pointer into a subdirectory
                    elseif ( $style == 1 ) $arrayPointer = & $arrayPointer[];        // Drop the pointer into a subdirectory
                    $arrayPointer = dirTreeToArray($newPath, $style);            // Process the new subdirectory
                  if ( $style == 1 ) sort($arrayPointer);    // Sort it if we're in a non-associative mode
                    $arrayPointer = & $dummyPointer;        // Bring the pointer back up a level
              }
                elseif ( is_file($newPath) ) $arrayPointer[] = $fileName;    // Enter the files
          }
      }
              return $tree;
  }
  else die("Failed to open directory $path in function dirTreeToArray(string \$path, \$style = {0, 1})");
}
?>


17-oct-2005 11:27

to: james dot d dot baker at gmail dot com
PHP has a builtin function  for doing what your function does,
http://php.net/ucfirst
http://php.net/ucwords


t0russ

to kristin at greenaple dot on dot ca:
thanx for sharing.
your function in recursive form proved to be slightly faster and it returns false (as it should) when the character is not found instead of number 0:
<?php
function strnposr($haystack, $needle, $occurance, $pos = 0) {
return ($occurance<2)?strpos($haystack, $needle, $pos):strnposr($haystack,$needle,$occurance-1,strpos($haystack, $needle, $pos) + 1);
}
?>


admin

This example lets you parse an unparsed strings variables. Warning: This could cause security leaks if you allow users to pass $variables through this engine. I recommend only using this for your Content Management System.
<?
$mytime=time();
$mydog="My Dog Ate My PHP!";
# Your Parsing String:
$s1 = 'Hyphen Variable Preserving: $mytime, and $mydog';
echo "Before:
$s1
";
# Remember, wherever you define this, it will not be defined GLOBAL into the function
# which is why we define it here. Defining it global could lead to security issues.
$vardata=get_defined_vars();
# Parse the string
$s1 = StrParse($s1,$vardata);
echo "After:
$s1";
function StrParse($str,$vardata) {
# Takes a string, or piece of data, that contains PHP Variables

# For example, unparsed variables like:  Test using time: $mytime
# This example shows $mytime, and not the actual variable value.
# The end result shows the actual variable value of $mytime.
# This is useful for building a content management system,
# and directing your variables into your content data,
# where content is stored in a file or database, unparsed.
# Of course this could slow down page loads, but it's a good way
# to parse data from current variables into your loaded new data
# making it compatible.

# Then the variables are replaced with the actual variable..
$getvarkeys=array_keys($vardata);
$ret=$str;
for ($x=0; $x < count($getvarkeys); $x++) {
$myvar=$getvarkeys[$x];
#echo "Variable: " . $myvar . " [" . $vardata[$myvar] . "]
";
$ret=str_replace('$' . $myvar, $vardata[$myvar], $ret);
}
return $ret;
}
?>


steverusin

The functions below:
function beginsWith( $str, $sub )
function endsWith( $str, $sub )
Are correct, but flawed.  You'd need to use the === operator instead:
function beginsWith( $str, $sub ) {
  return ( substr( $str, 0, strlen( $sub ) ) === $sub );
}
function endsWith( $str, $sub ) {
  return ( substr( $str, strlen( $str ) - strlen( $sub ) ) === $sub );
}
Otherwise, endsWith would return "foobar.0" ends with ".0" as well as "0" or "00" or any amount of zeros because numerically .0 does equal 0.


navarr

stripos for PHP4.x
<?php
 function stripos($haystack,$needle) {
   return strpos(strtoupper($haystack),strtoupper($needle));
 }
?>


da dot blayde a t gmail dot com

Sometimes when converting integers to strings, it looks better to have the number spelled out. I wrote this function that converts integers from -999 to 999 into spelled out strings:
function int2str($int=0){
$doOnes=true;
$neg=$int<0?true:false;
$int=abs(round($int));
$str='';
switch(strlen($int)){
 case 1:$int='0'.$int;
 case 2:$int='0'.$int;
 case 3:$int.='';break;
 default:return $int;
}
switch($int{0}){
 case 1:$str.='one-hundred-';break;
 case 2:$str.='two-hundred-';break;
 case 3:$str.='three-hundred-';break;
 case 4:$str.='four-hundred-';break;
 case 5:$str.='five-hundred-';break;
 case 6:$str.='six-hundred-';break;
 case 7:$str.='seven-hundred-';break;
 case 8:$str.='eight-hundred-';break;
 case 9:$str.='nine-hundred-';break;
}
switch($int{1}){
 case 1:
  switch($int{2}){
   case 0:$str.='ten-';break;
   case 1:$str.='eleven-';break;
   case 2:$str.='twelve-';break;
   case 3:$str.='thirteen-';break;
   case 4:$str.='fourteen-';break;
   case 5:$str.='fifteen-';break;
   case 6:$str.='sixteen-';break;
   case 7:$str.='seventeen-';break;
   case 8:$str.='eighteen-';break;
   case 9:$str.='nineteen-';break;
  }
  $doOnes=false;
 break;
 case 2:$str.='twenty-';break;
 case 3:$str.='thirty-';break;
 case 4:$str.='forty-';break;
 case 5:$str.='fifty-';break;
 case 6:$str.='sixty-';break;
 case 7:$str.='seventy-';break;
 case 8:$str.='eighty-';break;
 case 9:$str.='ninety-';break;
}
if($doOnes){
 switch($int{2}){
  case 1:$str.='one-';break;
  case 2:$str.='two-';break;
  case 3:$str.='three-';break;
  case 4:$str.='four-';break;
  case 5:$str.='five-';break;
  case 6:$str.='six-';break;
  case 7:$str.='seven-';break;
  case 8:$str.='eight-';break;
  case 9:$str.='nine-';break;
}}
$str=substr($str,0,-1);
if($neg){
 $str='negative '.$str;
}
if($int=='000'){
 $str='zero';
}
return $str;
}
Hope this helps someone,
-Blayde


m

Regarding the code for the function beginsWith($str, $sub), I found that it has problems when only one character is present after the string searched for. I found that this works better instead:
<?php
function beginsWith($str, $sub) {
return (strncmp($str, $sub, strlen($sub)) == 0);
}
?>


21-dec-2004 04:31

In response to hackajar <matt> yahoo <trot> com,
No string-to-array function exists because it is not needed. If you reference a string with an offset like you do with an array, the character at that offset will be return. This is documented in section III.11's "Strings" article under the "String access and modification by character" heading.


moe

In responce to mike here is a better random string function
<?php
function random_string($max = 20){
$chars = "abcdefghijklmnopqrstuvwxwz0123456789_";
for($i = 0; $i < $max; $i++){
$rand_key = mt_rand(0, strlen($chars));
$string  .= substr($chars, $rand_key, 1);
}
return str_shuffle($string);
}
?>


mickycole

In responce to James Baker's sencence case function.
Great function however i would make one slight variation being that it doesn't take into account the fact that a capital is required after a new paragraph so i modified it to check for /r and /n as follows:
<?PHP
/*/ Author : James Baker /*/
function sentenceCase($s){
  $str = strtolower($s);
  $cap = true;
 
  for($x = 0; $x < strlen($str); $x++){
      $letter = substr($str, $x, 1);
      if($letter == "." || $letter == "!" || $letter == "?" || $letter == "\n" || $letter == "\r"){
          $cap = true;
      }elseif($letter != " " && $cap == true){
          $letter = strtoupper($letter);
          $cap = false;
      }
     
      $ret .= $letter;
  }
 
  return $ret;
}
?>


administrador ensaimada sphoera punt com

I've prepared this simple function to obtain a string delimited between tags (not only XML tags!). Anybody needs something like this?.
<?php
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$string = "this [custom] function is useless!!";
echo get_string_between($string,"[","]");
// must return "custom";
?>
more functions at http://www.sphoera.com


andy a t onesandzeros d o t biz

I use these little doo-dads quite a bit. I just thought I'd share them and maybe save someone a little time. No biggy. :)
// returns true if $str begins with $sub
function beginsWith( $str, $sub ) {
return ( substr( $str, 0, strlen( $sub ) ) == $sub );
}
// return tru if $str ends with $sub
function endsWith( $str, $sub ) {
return ( substr( $str, strlen( $str ) - strlen( $sub ) ) == $sub );
}
// trims off x chars from the front of a string
// or the matching string in $off is trimmed off
function trimOffFront( $off, $str ) {
if( is_numeric( $off ) )
return substr( $str, $off );
else
return substr( $str, strlen( $off ) );
}
// trims off x chars from the end of a string
// or the matching string in $off is trimmed off
function trimOffEnd( $off, $str ) {
if( is_numeric( $off ) )
return substr( $str, 0, strlen( $str ) - $off );
else
return substr( $str, 0, strlen( $str ) - strlen( $off ) );
}


heavyraptor

I think that
administrador(ensaimada)sphoera(punt)com's function is
too complicated. It's easier with regular expressions.
So I made this function, it isn't really the same,
it's even better because it returns an array with all the
matches found
If there are no matches, false is returned.
<?php
// bool/array str_between( string str, string
start_str, string end_str )
function str_between($str,$start,$end) {
 if (preg_match_all('/' . preg_quote($start) . '(.*?)' . preg_quote($end) . '/',$str,$matches)) {
  return $matches[1];
 }
 // no matches
 return false;
}
?>
Enjoy


kristin

I really searched for a function that would do this as I've seen it in other languages but I couldn't find it here. This is particularily useful when combined with substr() to take the first part of a string up to a certain point.
strnpos() - Find the nth position of needle in haystack.
<?php
function strnpos($haystack, $needle, $occurance, $pos = 0) {

for ($i = 1; $i <= $occurance; $i++) {
$pos = strpos($haystack, $needle, $pos) + 1;
}
return $pos - 1;

}
?>
Example: Give me everything up to the fourth occurance of '/'.
<?php
$haystack = "/home/username/www/index.php";
$needle = "/";

$root_dir = substr($haystack, 0, strnpos($haystack, $needle, 4));

echo $root_dir;

?>
Returns: /home/username/www
Use this example with the server variable $_SERVER['SCRIPT_NAME'] as the haystack and you can self-discover a document's root directory for the purposes of locating global files automatically!


dkflbk

I needed str2bin() function for one of my project, so if some one else is want to use it, have fun :)
<?php
/**
* Returns an ASCII string containing
* the binary representation of the input data .
**/
function str2bin($str, $mode=0) {
$out = false;
for($a=0; $a < strlen($str); $a++) {
$dec = ord(substr($str,$a,1));
$bin = '';
for($i=7; $i>=0; $i--) {
if ( $dec >= pow(2, $i) ) {
$bin .= "1";
$dec -= pow(2, $i);
} else {
$bin .= "0";
}
}
/* Default-mode */
if ( $mode == 0 ) $out .= $bin;
/* Human-mode (easy to read) */
if ( $mode == 1 ) $out .= $bin . " ";
/* Array-mode (easy to use) */
if ( $mode == 2 ) $out[$a] = $bin;
}
return $out;
}
?>


admin

Here's an easier way to find nth...
function nth($numbex){
 if ($numbex%10 == 1 && $numbex%100 != 11) $sth='st';
 elseif ($numbex%10 == 2 && $numbex%100 != 12) $sth='nd';
 elseif ($numbex%10 == 3 && $numbex%100 != 13) $sth='rd';
 else $sth = 'th';
 return $sth;
}
there is is no need to check if the user has entered a non-integer as we may be using this function for expressing variables as well eg. ith value of x , nth root of z ,etc...


terry dot greenlaw

Here's a simpler "simplest" way to toggle through a set of 1..n colors for web backgrounds:
<?php
$colours = array('#000000', '#808080', '#A0A0A0', '#FFFFFF');
// Get a colour
$color = next($colors) or $color = reset($colors);
?>
The code doesn't need to know anything about the number of elements being cycled through. That way you won't have to tracking down all the code when changing the number of colors or the color values.


mike "eyes" moe

Here is a truly random string generator it uses the most common string functions it will work on anywhere.
<?php
function random_string($max = 20){
$chars = explode(" ", "a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9");
for($i = 0; $i < $max; $i++){
$rnd = array_rand($chars);
$rtn .= base64_encode(md5($chars[$rnd]));
}
return substr(str_shuffle(strtolower($rtn)), 0, $max);
}
?>


pommef

Example: Give me everything up to the fourth occurance of '/'.
<?php
  $haystack = "/home/username/www/index.php";
  $needle = "/";
 
  function strnpos($haystack, $needle, $occurance, $pos = 0) {

$res = implode($needle,$haystack);

$res = array_slice($res, $pos,  $occurance);

return explode ($needle,$res);
}
?>


janturon

be aware of this string behavior:
$array= "foo";
echo $array["bar"]; // "f"
explanation:
$array is string, so $array["bar"] is evaluated as $array[0] and this is the first character of "foo".
if someone passes string into your associative array (get, post or cookie), it is security risk, i.e.:
isset($array["user_exists"]); // true!
use array_key_exists() instead!


benjamin

An update to admin at fivestarbuy dot com's StrParse. Since php5.2.x the occurance of an object in the vardata will cause a "Catchable fatal error". Previously it has failed silently, so I added nullification of present objects.
I also updated comments to be more specific, I hope that's ok with you, admin at fivestarbuy dot com:
<?php
function StrParse($str,$vardata) {
# Variables present in $str is replaced by values of variables in $vardata
# typical use:
# $vardata = get_defined_vars();
# $str = some template code with variables present.
# uncomment the echo line to debug.
$getvarkeys=array_keys($vardata);
$ret=$str;
for ($x=0; $x < count($getvarkeys); $x++) {
  $myvar=$getvarkeys[$x];
  if(is_object($vardata[$myvar])) $vardata[$myvar] = null;
  #echo "Variable: " . $myvar . " [" . $vardata[$myvar] . "]
";
  $ret=str_replace('$' . $myvar, $vardata[$myvar], $ret);
}
return $ret;
}
?>


webmaster

A comprehensive concatenation function, that works with array and strings
<?php
function str_cat() {
 $args = func_get_args() ;

 // Asserts that every array given as argument is $dim-size.
 // Keys in arrays are stripped off.
 // If no array is found, $dim stays unset.
 foreach($args as $key => $arg) {
   if(is_array($arg)) {
     if(!isset($dim))
       $dim = count($arg) ;
     elseif($dim != count($arg))
       return FALSE ;
     $args[$key] = array_values($arg) ;
   }
 }

 // Concatenation
 if(isset($dim)) {
   $result = array() ;
   for($i=0;$i<$dim;$i++) {
     $result[$i] = '' ;
     foreach($args as $arg)
       $result[$i] .= ( is_array($arg) ? $arg[$i] : $arg ) ;
   }
   return $result ;
 } else {
   return implode($args) ;
 }
}
?>
A simple example :
<?php
str_cat(array(1,2,3), '-', array('foo' => 'foo', 'bar' => 'bar', 'noop' => 'noop')) ;
?>
will return :
Array (
 [0] => 1-foo
 [1] => 2-bar
 [2] => 3-noop
)
More usefull :
<?php
$myget = $_GET ; // retrieving previous $_GET values
$myget['foo'] = 'b a r' ; // changing one value
$myget = str_cat(array_keys($myget), '=', array_map('rawurlencode', array_values($myget))) ;
$querystring = implode(ini_get('arg_separator.output'), $myget)) ;
?>
will return a valid querystring with some values changed.
Note that <?php str_cat('foo', '&', 'bar') ; ?> will return 'foo&bar', while <?php str_cat(array('foo'), '&', 'bar') ; ?> will return array(0 => foo&bar)


tab!

//
// string strtrmvistl(  string str, [int maxlen = 64],
//                      [bool right_justify = false],
//                      [string delimter = "
\n"])
//
// splits a long string into two chunks (a start and an end chunk)
// of a given maximum length and seperates them by a given delimeter.
// a second chunk can be right-justified within maxlen.
// may be used to 'spread' a string over two lines.
//
function strtrmvistl($str, $maxlen = 64, $right_justify = false, $delimter = "
\n") {
if(($len = strlen($str = chop($str))) > ($maxlen = max($maxlen, 12))) {
$newstr = substr($str, 0, $maxlen - 3);
if($len > ($maxlen - 3)) {
$endlen = min(($len - strlen($newstr)), $maxlen - 3);
$newstr .= "..." . $delimter;
if($right_justify)
$newstr .= str_pad('', $maxlen - $endlen - 3, ' ');
$newstr .= "..." . substr($str, $len - $endlen);
}
return($newstr);
}
return($str);
}


tim_meredith

--Convert MSWord Quotes--
Use this before any conversion to HTML entities or characters to clean up a form entry cut and pasted from MSWord.
function fixword($scratch)
{
$start=chr(226).chr(128);
$word=array();$fixword=array();
$word[]=$start.chr(152);$fixword[]="'";
$word[]=$start.chr(153);$fixword[]="'";
$word[]=$start.chr(156);$fixword[]="\"";
$word[]=$start.chr(157);$fixword[]="\"";
return str_replace($word, $fixword, $scratch);
}


james dot d dot baker

<?php
/*
Written By James Baker, May 27th 2005
sentenceCase($string);
$string: The string to convert to sentence case.
Converts a string into proper sentence case (First letter of each sentance capital, all the others smaller)
Example Usage:
echo sentenceCase("HELLO WORLD!!! THIS IS A CAPITALISED SENTENCE. this isn't.");
Returns:
Hello world!!! This is a capitalised sentence. This isn't.
*/
function sentenceCase($s){
$str = strtolower($s);
$cap = true;

for($x = 0; $x < strlen($str); $x++){
$letter = substr($str, $x, 1);
if($letter == "." || $letter == "!" || $letter == "?"){
$cap = true;
}elseif($letter != " " && $cap == true){
$letter = strtoupper($letter);
$cap = false;
}

$ret .= $letter;
}

return $ret;
}
?>


rh

<?php
/**
Utility class: static methods for cleaning & escaping untrusted (i.e.
user-supplied) strings.
Any string can (usually) be thought of as being in one of these 'modes':
pure = what the user actually typed / what you want to see on the page /
      what is actually stored in the DB
gpc  = incoming GET, POST or COOKIE data
sql  = escaped for passing safely to RDBMS via SQL (also, data from DB
      queries and file reads if you have magic_quotes_runtime on--which
      is rare)
html = safe for html display (htmlentities applied)
Always knowing what mode your string is in--using these methods to
convert between modes--will prevent SQL injection and cross-site scripting.
This class refers to its own namespace (so it can work in PHP 4--there is no
self keyword until PHP 5). Do not change the name of the class w/o changing
all the internal references.
Example usage: a POST value that you want to query with:
$username = Str::gpc2sql($_POST['username']);
*/
//This sets SQL escaping to use slashes; for Sybase(/MSSQL)-style escaping
// ( ' --> '' ), set to true.
define('STR_SYBASE', false);
class Str {
   function gpc2sql($gpc, $maxLength = false)
   {
       return Str::pure2sql(Str::gpc2pure($gpc), $maxLength);
   }
   function gpc2html($gpc, $maxLength = false)
   {
       return Str::pure2html(Str::gpc2pure($gpc), $maxLength);
   }
   function gpc2pure($gpc)
   {
       if (ini_get('magic_quotes_sybase'))
           $pure = str_replace("''", "'", $gpc);
       else $pure = get_magic_quotes_gpc() ? stripslashes($gpc) : $gpc;
       return $pure;
   }
   function html2pure($html)
   {
       return html_entity_decode($html);
   }
   function html2sql($html, $maxLength = false)
   {
       return Str::pure2sql(Str::html2pure($html), $maxLength);
   }
   function pure2html($pure, $maxLength = false)
   {
       return $maxLength ? htmlentities(substr($pure, 0, $maxLength))
                         : htmlentities($pure);
   }
   function pure2sql($pure, $maxLength = false)
   {
       if ($maxLength) $pure = substr($pure, 0, $maxLength);
       return (STR_SYBASE)
              ? str_replace("'", "''", $pure)
              : addslashes($pure);
   }
   function sql2html($sql, $maxLength = false)
   {
       $pure = Str::sql2pure($sql);
       if ($maxLength) $pure = substr($pure, 0, $maxLength);
       return Str::pure2html($pure);
   }
   function sql2pure($sql)
   {
       return (STR_SYBASE)
              ? str_replace("''", "'", $sql)
              : stripslashes($sql);
   }
}
?>


php

<?php
 /*
 * str_match
 *
 * return a string with only cacacteres defined in a expression return false if the expression is not valid
 *
 * @param $str string the string
 * @param $match the expression based on the class definition off a PCRE regular expression.
 *   the '[', ']', '\' and '^' at class start need to be escaped.
 *   like : -a-z0-9_@.
 */
 function str_match( $str, $match )
 {
   $return = '';
   if( eregi( '(.*)', $match, $class ) )
   {
     $match = '['.$regs[1].']';
     for( $i=0; $i<strlen($str); $i++ )
     if( ereg( '['.$class[1].']', $str[$i] ) )
     $return .= $str{$i};
     return $return;
   }
   else return false;
 }
 /*
 * example
 * accept only alphanum caracteres from the GET/POST parameters 'a'
 */
 if( ! empty($_REQUEST['a']) )
   $_REQUEST['a'] = str_match( $_REQUEST['a'], 'a-zA-Z0-9' );
 else
   $_REQUEST['a'] = 'default';
?>


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