*/
function cologne_phon($word){
/**
* @param string $word string to be analyzed
* @return string $value represents the Kölner Phonetik value
* @access public
*/
//prepare for processing
$word=strtolower($word);
$substitution=array(
"ä"=>"a",
"ö"=>"o",
"ü"=>"u",
"ß"=>"ss",
"ph"=>"f"
);
foreach ($substitution as $letter=>$substitution) {
$word=str_replace($letter,$substitution,$word);
}
$len=strlen($word);
//Rule for exeptions
$exceptionsLeading=array(
4=>array("ca","ch","ck","cl","co","cq","cu","cx"),
8=>array("dc","ds","dz","tc","ts","tz")
);
$exceptionsFollowing=array("sc","zc","cx","kx","qx");
//Table for coding
$codingTable=array(
0=>array("a","e","i","j","o","u","y"),
1=>array("b","p"),
2=>array("d","t"),
3=>array("f","v","w"),
4=>array("c","g","k","q"),
48=>array("x"),
5=>array("l"),
6=>array("m","n"),
7=>array("r"),
8=>array("c","s","z"),
);
for ($i=0;$i<$len;$i++){
$value[$i]="";
//Exceptions
if ($i==0 AND $word[$i].$word[$i+1]=="cr") $value[$i]=4;
foreach ($exceptionsLeading as $code=>$letters) {
if (in_array($word[$i].$word[$i+1],$letters)){
$value[$i]=$code;
} }
if ($i!=0 AND (in_array($word[$i-1].$word[$i],
$exceptionsFollowing))) {
value[$i]=8;
}
//Normal encoding
if ($value[$i]==""){
foreach ($codingTable as $code=>$letters) {
if (in_array($word[$i],$letters))$value[$i]=$code;
}
}
}
//delete double values
$len=count($value);
for ($i=1;$i<$len;$i++){
if ($value[$i]==$value[$i-1]) $value[$i]="";
}
//delete vocals
for ($i=1;$i>$len;$i++){//omitting first characer code and h
if ($value[$i]==0) $value[$i]="";
}
$value=array_filter($value);
$value=implode("",$value);
return $value;
}
?>
<
9 Dirk Hoeschen - Feenders de ¶3 years ago~
I made some improvements to the "Cologne Phonetic" function of niclas
zimmer. Key and value of the arrays are inverted to uses simple arrays
instead of multidimensional arrays. Therefore all loops and iterations
are not longer necessary to find the matching value for a char. I
put the function into a static class and moved the array declarations
outside the function.
The result is more reliable and five times faster than the original.
>
4, "ch" => 4, "ck" => 4, "cl" => 4, "co" => 4, "cq" => 4, "cu" => 4, "cx" => 4, "dc" => 8, "ds" => 8, "dz" => 8, "tc" => 8, "ts" => 8, "tz" => 8);
static $eFollow = array("sc", "zc", "cx", "kx", "qx");
static $codingTable = array("a" => 0, "e" => 0, "i" => 0, "j" => 0, "o" => 0, "u" => 0, "y" => 0,
"b" => 1, "p" => 1, "d" => 2, "t" => 2, "f" => 3, "v" => 3, "w" => 3, "c" => 4, "g" => 4, "k" => 4, "q" => 4,
"x" => 48, "l" => 5, "m" => 6, "n" => 6, "r" => 7, "c" => 8, "s" => 8, "z" => 8);
public static function getCologneHash($word)
{
if (empty($word)) return false;
$len = strlen($word);
for ($i = 0; $i < $len; $i++) {
$value[$i] = "";
//Exceptions
if ($i == 0 && $word[$i] . $word[$i + 1] == "cr") {
$value[$i] = 4;
}
if (isset($word[$i + 1]) && isset(self::$eLeading[$word[$i] . $word[$i + 1]])) {
$value[$i] = self::$eLeading[$word[$i] . $word[$i + 1]];
}
if ($i != 0 && (in_array($word[$i - 1] . $word[$i], self::$eFollow))) {
$value[$i] = 8;
}
// normal encoding
if ($value[$i]=="") {
if (isset(self::$codingTable[$word[$i]])) {
$value[$i] = self::$codingTable[$word[$i]];
}
}
}
// delete double values
$len = count($value);
for ($i = 1; $i < $len; $i++) {
if ($value[$i] == $value[$i - 1]) {
$value[$i] = "";
}
}
// delete vocals
for ($i = 1; $i > $len; $i++) {
// omitting first characer code and h
if ($value[$i] == 0) {
$value[$i] = "";
}
}
$value = array_filter($value);
$value = implode("", $value);
return $value;
}
}
?>
<
--------------------------------------------------------------------------------
*sprintf*
+---------+~
| sprintf |~
+---------+~
(PHP 4, PHP 5, PHP 7)
sprintf — Return a formatted string
Description~
>
string sprintf ( string $format [, mixed $args [, mixed $... ]] )
<
Returns a string produced according to the formatting string format.
Parameters~
format
------
The format string is composed of zero or more directives: ordinary
characters (excluding %) that are copied directly to the result, and
conversion specifications, each of which results in fetching its own
parameter. This applies to both sprintf() and printf().
Each conversion specification consists of a percent sign (%), followed by one or more of these elements, in order:
An optional sign specifier that forces a sign (- or +) to be used on a
number. By default, only the - sign is used on a number if it's
negative. This specifier forces positive numbers to have the + sign
attached as well.
An optional padding specifier that says what character will be used
for padding the results to the right string size. This may be a space
character or a 0 (zero character). The default is to pad with spaces.
An alternate padding character can be specified by prefixing it with a
single quote ('). See the examples below.
An optional alignment specifier that says if the result should be
left-justified or right-justified. The default is right-justified; a -
character here will make it left-justified.
An optional number, a width specifier that says how many characters
(minimum) this conversion should result in.
An optional precision specifier in the form of a period (.) followed
by an optional decimal digit string that says how many decimal digits
should be displayed for floating-point numbers. When using this
specifier on a string, it acts as a cutoff point, setting a maximum
character limit to the string. Additionally, the character to use when
padding a number may optionally be specified between the period and
the digit.
A type specifier that says what type the argument data should be
treated as. Possible types:
% - a literal percent character. No argument is required.
b - the argument is treated as an integer, and presented as a binary number.
c - the argument is treated as an integer, and presented as the character with that ASCII value.
d - the argument is treated as an integer, and presented as a (signed) decimal number.
e - the argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less).
E - like %e but uses uppercase letter (e.g. 1.2E+2).
f - the argument is treated as a float, and presented as a floating-point number (locale aware).
F - the argument is treated as a float, and presented as a floating-point number (non-locale aware). Available since PHP 5.0.3.
g - shorter of %e and %f.
G - shorter of %E and %f.
o - the argument is treated as an integer, and presented as an octal number.
s - the argument is treated as and presented as a string.
u - the argument is treated as an integer, and presented as an unsigned decimal number.
x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).
Variables will be co-erced to a suitable type for the specifier:
Type Handling
Type Specifiers
string s
integer d, u, c, o, x, X, b
double g, G, e, E, f, F
Warning
Attempting to use a combination of the string and width specifiers
with character sets that require more than one byte per character may
result in unexpected results
The format string supports argument numbering/swapping. Here is an example:
Example #1 Argument swapping
>
<
This will output "There are 5 monkeys in the tree". But imagine we are
creating a format string in a separate file, commonly because we would
like to internationalize it and we rewrite it as:
Example #2 Argument swapping
>
<
We now have a problem. The order of the placeholders in the format
string does not match the order of the arguments in the code. We would
like to leave the code as is and simply indicate in the format string
which arguments the placeholders refer to. We would write the format
string like this instead:
Example #3 Argument swapping
>
<
An added benefit here is that you can repeat the placeholders without
adding more arguments in the code. For example:
Example #4 Argument swapping
>
<
When using argument swapping, the n$ position specifier must come
immediately after the percent sign (%), before any other specifiers,
as shown in the example below.
Example #5 Specifying padding character
>
<
The above example will output:
......123
000000123
Example #6 Position specifier with other specifiers
>
<
The above example will output:
The tree contains 0005 monkeys
Note:
Attempting to use a position specifier greater than PHP_INT_MAX will
result in sprintf() generating warnings.
Warning
The c type specifier ignores padding and width
args
...
Return Values~
Returns a string produced according to the formatting string format,
or FALSE on failure.
Examples~
Example #7 printf(): various examples
>
<
The above example will output:
%b = '10100111101010011010101101'
%c = 'A'
%d = '43951789'
%e = '4.39518e+7'
%u = '43951789'
%u = '4251015507'
%f = '43951789.000000'
%o = '247523255'
%s = '43951789'
%x = '29ea6ad'
%X = '29EA6AD'
%+d = '+43951789'
%+d = '-43951789'
Example #8 printf(): string specifiers
>
<
The above example will output:
[monkey]
[ monkey]
[monkey ]
[0000monkey]
[####monkey]
[many monke]
Example #9 sprintf(): zero-padded integers
>
<
Example #10 sprintf(): formatting currency
>
<
Example #11 sprintf(): scientific notation
>
<
See Also~
|printf|() - Output a formatted string
|sscanf|() - Parses input from a string according to a format
|fscanf|() - Parses input from a file according to a format
|vsprintf|() - Return a formatted string
|number_format|() - Format a number with grouped thousands
|date|() - Format a local time/date
User Contributed Notes 59 notes
43 Alex R. Gibbs ¶4 years ago~
1. A plus sign ('+') means put a '+' before positive numbers while a
minus sign ('-') means left justify. The documentation incorrectly
states that they are interchangeable. They produce unique results
that can be combined:
>
<
outputs:
| +1| -1|
|1 |-1 |
|+1 |-1 |
2. Padding with a '0' is different than padding with other
characters. Zeros will only be added at the front of a number, after
any sign. Other characters will be added before the sign, or after
the number:
>
<
outputs:
|-002|
|::-2|
|-2::|
|-2 |
|-211|
|-2 |
23 remy dot damour at -please-no-spam-laposte dot net ¶8 years ago~
With printf() and sprintf() functions, escape character is not
backslash '\' but rather '%'.
Ie. to print '%' character you need to escape it with itself:
>
<
6 timo dot frenay at gmail dot com ¶5 years ago~
Here is how to print a floating point number with 16 significant
digits regardless of magnitude:
>
<
This works more reliably than doing something like sprintf('%.15F',
$value) as the latter may cut off significant digits for very small
numbers, or prints bogus digits (meaning extra digits beyond what can
reliably be represented in a floating point number) for very large
numbers.
6 viktor at textalk dot com ¶8 years ago~
A more complete and working version of mb_sprintf and mb_vsprintf. It
should work with any "ASCII preserving" encoding such as UTF-8 and all
the ISO-8859 charsets. It handles sign, padding, alignment, width and
precision. Argument swapping is not handled.
>
0 && mb_strlen($arg,$encoding) > $precision)
$arg = mb_substr($precision,0,$precision,$encoding);
}
// define padding
if ($size > 0) {
$arglen = mb_strlen($arg, $encoding);
if ($arglen < $size) {
if($filler==='')
$filler = ' ';
if ($align == '-')
$padding_post = str_repeat($filler, $size - $arglen);
else
$padding_pre = str_repeat($filler, $size - $arglen);
}
}
// escape % and pass it forward
$newformat .= $padding_pre . str_replace('%', '%%', $arg) . $padding_post;
}
else {
// another type, pass forward
$newformat .= "%$sign$filler$align$size$precision$type";
$newargv[] = array_shift($argv);
}
$format = strval($post);
}
// Convert new format back from UTF-8 to the original encoding
$newformat = mb_convert_encoding($newformat, $encoding, 'UTF-8');
return vsprintf($newformat, $newargv);
}
}
?>
<
6 php at sharpdreams dot com ¶12 years ago~
Note that when using the argument swapping, you MUST number every
argument, otherwise sprintf gets confused. This only happens if you
use number arguments first, then switch to a non-numbered, and then
back to a numbered one.
>
<
3 no dot email dot address at example dot com ¶14 years ago~
Using argument swapping in sprintf() with gettext: Let's say you've
written the following script:
>
<
Now you run xgettext in order to generate a .po file. The .po file
will then look like this:
#: file.php:9
#, ycp-format
msgid "The %2\\$s contains %1\\$d monkeys"
msgstr ""
Notice how an extra backslash has been added by xgettext.
Once you've translated the string, you must remove all backslashes
from the ID string as well as the translation, so the po file will
look like this:
#: file.php:9
#, ycp-format
msgid "The %2$s contains %1$d monkeys"
msgstr "Der er %1$d aber i %2$s"
Now run msgfmt to generate the .mo file, restart Apache to remove the gettext cache if necessary, and you're off.
8 Pacogliss ¶11 years ago~
Just a reminder for beginners : example 6 'printf("[%10s]\n", $s);'
only works (that is, shows out the spaces) if you put the html
' ' tags ( head-scraping time saver ;-).
--------------------------------------------------------------------------------
*sscanf*
+--------+~
| sscanf |~
+--------+~
(PHP 4 >= 4.0.1, PHP 5, PHP 7)
sscanf — Parses input from a string according to a format
Description~
>
mixed sscanf ( string $str , string $format [, mixed &$... ] )
<
The function sscanf() is the input analog of printf(). sscanf() reads
from the string str and interprets it according to the specified
format, which is described in the documentation for sprintf().
Any whitespace in the format string matches any whitespace in the
input string. This means that even a tab \t in the format string can
match a single space character in the input string.
Parameters~
str
-----
The input string being parsed.
format
------
The interpreted format for str, which is described in the
documentation for sprintf() with following differences:
Function is not locale-aware.
F, g, G and b are not supported.
D stands for decimal number.
i stands for integer with base detection.
n stands for number of characters processed so far.
...
Optionally pass in variables by reference that will contain the parsed
values.
Return Values~
If only two parameters were passed to this function, the values parsed
will be returned as an array. Otherwise, if optional parameters are
passed, the function will return the number of assigned values. The
optional parameters must be passed by reference.
If there are more substrings expected in the format than there are available within str, -1 will be returned.
Examples~
Example #1 sscanf() Example
>
<
If optional parameters are passed, the function will return the number of assigned values.
Example #2 sscanf() - using optional parameters
>
$first
$last
\n";
?>
<
See Also~
|fscanf|() - Parses input from a file according to a format
|printf|() - Output a formatted string
|sprintf|() - Return a formatted string
User Contributed Notes 17 notes
47 jon at fuck dot org ¶14 years ago~
this function is a great way to get integer rgb values from the html
equivalent hex.
list($r, $g, $b) = sscanf('00ccff', '%2x%2x%2x');
19 mikewillitsgmail.com ¶9 years ago~
FYI - if you are trying to scan from a string which contains a
filename with extension. For instance:
>
<
The scanned string in the $fpart1 parameter turns out to be 'name.gif'
and $fpart2 will be NULL.
To get around this you can simply replace the "." with a space or
another "white-space like" string sequence.
I didn't see any other comments on regarding string literals which
contain a '.' so I thought I'd mention it. The subtle characteristics
of having "white-space delimited" content I think can be a source of
usage contention. Obviously, another way to go is regular expressions
in this instance, but for newer users this may be helpful.
Just in case someone else spent 10 minutes of frustration like I did.
This was seen on PHP Version 5.2.3-1ubuntu6.3.
Searching the bug reports shows another users misunderstanding:
http://bugs.php.net/bug.php?id=7793
--------------------------------------------------------------------------------
*str_getcsv*
+------------+~
| str_getcsv |~
+------------+~
(PHP 5 >= 5.3.0, PHP 7)
str_getcsv — Parse a CSV string into an array
Description~
>
array str_getcsv ( string $input [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]] )
<
Parses a string input for fields in CSV format and returns an array
containing the fields read.
Parameters~
input
-----
The string to parse.
delimiter
-----
Set the field delimiter (one character only).
enclosure
---------
Set the field enclosure character (one character only).
escape
------
Set the escape character (one character only). Defaults as a backslash
(\)
Return Values~
Returns an indexed array containing the fields read.
See Also~
|fgetcsv|() - Gets line from file pointer and parse for CSV fields
User Contributed Notes 37 notes
270 james at moss dot io ¶2 years ago~
Handy one liner to parse a CSV file into an array
>
<
9 dejiakala at gmail dot com ¶2 years ago~
I wanted the best of the 2 solutions by james at moss dot io and Jay
Williams (csv_to_array()) - create associative array from a CSV file
with a header row.
>
<
Then I thought why not try some benchmarking? I grabbed a sample CSV
file with 50,000 rows (10 columns each) and Vulcan Logic Disassembler
(VLD) which hooks into the Zend Engine and dumps all the opcodes
(execution units) of a script - see http://pecl.php.net/package/vld
and example here:
http://fabien.potencier.org/article/8/print-vs-echo-which-one-is-faster
Result:
array_walk() and array_map() - 39 opcodes
csv_to_array() - 69 opcodes
51 starrychloe at oliveyou dot net ¶1 year ago~
Based on James' line, this will create an array of associative arrays
with the first row column headers as the keys.
>
<
This will yield something like
[2] => Array
(
[Campaign ID] => 295095038
[Ad group ID] => 22460178158
[Keyword ID] => 3993587178
80 durik at 3ilab dot net ¶6 years ago~
As the str_getcsv(), unlike to fgetcsv(), does not parse the rows in
CSV string, I have found following easy workaround:
>
<
Why not use explode() instead of str_getcsv() to parse rows? Because
explode() would not treat possible enclosured parts of string or
escaped characters correctly.
58 Jay Williams ¶6 years ago~
Here is a quick and easy way to convert a CSV file to an associated
array:
>
<
17 Ryan Rubley ¶3 years ago~
@normadize - that is a nice start, but it fails on situations where a
field is empty but quoted (returning a string with one double quote
instead of an empty string) and cases like """""foo""""" that should
result in ""foo"" but instead return "foo". I also get a row with 1
empty field at the end because of the final CRLF in the CSV. Plus, I
don't really like the !!Q!! magic or urlencoding to get around things.
Also, \R doesn't work in pcre on any of my php installations.
Here is my take on this, without anonymous functions (so it works on
PHP < 5.3), and without your options (because I believe the only
correct way to parse according to the RFC would be $skip_empty_lines =
false and $trim_fields = false).
>
//parse a CSV file into a two-dimensional array
//this seems as simple as splitting a string by lines and commas, but this only works if tricks are performed
//to ensure that you do NOT split on lines and commas that are inside of double quotes.
function parse_csv($str)
{
//match all the non-quoted text and one series of quoted text (or the end of the string)
//each group of matches will be parsed with the callback, with $matches[1] containing all the non-quoted text,
//and $matches[3] containing everything inside the quotes
$str = preg_replace_callback('/([^"]*)("((""|[^"])*)"|$)/s', 'parse_csv_quotes', $str);
//remove the very last newline to prevent a 0-field array for the last line
$str = preg_replace('/\n$/', '', $str);
//split on LF and parse each line with a callback
return array_map('parse_csv_line', explode("\n", $str));
}
//replace all the csv-special characters inside double quotes with
//markers using an escape sequence
function parse_csv_quotes($matches)
{
//anything inside the quotes that might be used to split the string into lines and fields later,
//needs to be quoted. The only character we can guarantee as safe to use, because it will never appear in the unquoted text, is a CR
//So we're going to use CR as a marker to make escape sequences for CR, LF, Quotes, and Commas.
$str = str_replace("\r", "\rR", $matches[3]);
$str = str_replace("\n", "\rN", $str);
$str = str_replace('""', "\rQ", $str);
$str = str_replace(',', "\rC", $str);
//The unquoted text is where commas and newlines are allowed, and where the splits will happen
//We're going to remove all CRs from the unquoted text, by normalizing all line endings to just LF
//This ensures us that the only place CR is used, is as the escape sequences for quoted text
return preg_replace('/\r\n?/', "\n", $matches[1]) . $str;
}
//split on comma and parse each field with a callback
function parse_csv_line($line)
{
return array_map('parse_csv_field', explode(',', $line));
}
//restore any csv-special characters that are part of the data
function parse_csv_field($field) {
$field = str_replace("\rC", ',', $field);
$field = str_replace("\rQ", '"', $field);
$field = str_replace("\rN", "\n", $field);
$field = str_replace("\rR", "\r", $field);
return $field;
}
<
16 normadize -a- gmail -d- com ¶4 years ago~
Like some other users here noted, str_getcsv() cannot be used if you
want to comply with either the RFC or with most spreadsheet tools like
Excel or Google Docs.
These tools do not escape commas or new lines, but instead place
double-quotes (") around the field. If there are any double-quotes in
the field, these are escaped with another double-quote (" becomes "").
All this may look odd, but it is what the RFC and most tools do ...
For instance, try exporting as .csv a Google Docs spreadsheet (File >
Download as > .csv) which has new lines and commas as part of the
field values and see how the .csv content looks, then try to parse it
using str_getcsv() ... it will spectacularly regardless of the
arguments you pass to it.
Here is a function that can handle everything correctly, and more:
- doesn't use any for or while loops,
- it allows for any separator (any string of any length),
- option to skip empty lines,
- option to trim fields,
- can handle UTF8 data too (although .csv files are likely non-unicode).
Here is the more human readable version of the function:
>
<
Since this is not using any loops, you can actually write it as a
one-line statement (one-liner).
Here's the function using just one line of code for the function body,
formatted nicely though:
>
<
Replace !!Q!! with another placeholder if you wish.
Have fun.
--------------------------------------------------------------------------------
*str_ireplace*
+--------------+~
| str_ireplace |~
+--------------+~
(PHP 5, PHP 7)
str_ireplace — Case-insensitive version of str_replace().
Description
>
mixed str_ireplace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
<
This function returns a string or an array with all occurrences of
search in subject (ignoring case) replaced with the given replace
value. If you don't need fancy replacing rules, you should generally
use this function instead of preg_replace() with the i modifier.
Parameters~
If search and replace are arrays, then str_ireplace() takes a value
from each array and uses them to search and replace on subject. If
replace has fewer values than search, then an empty string is used for
the rest of replacement values. If search is an array and replace is a
string, then this replacement string is used for every value of
search. The converse would not make sense, though.
If search or replace are arrays, their elements are processed first to
last.
search
------
The value being searched for, otherwise known as the needle. An array
may be used to designate multiple needles.
replace
-------
The replacement value that replaces found search values. An array may
be used to designate multiple replacements.
subject
-------
The string or array being searched and replaced on, otherwise known as
the haystack.
If subject is an array, then the search and replace is performed with
every entry of subject, and the return value is an array as well.
count
-----
If passed, this will be set to the number of replacements performed.
Return Values~
Returns a string or an array of replacements.
Examples~
Example #1 str_ireplace() example
>
");
echo $bodytag; //
?>
<
Notes
Note: This function is binary-safe.
Caution
Replacement order gotcha
Because str_ireplace() replaces left to right, it might replace a
previously inserted value when doing multiple replacements. Example #2
in the str_replace() documentation demonstrates how this may affect
you in practice.
See Also~
|str_replace|() - Replace all occurrences of the search string with the replacement string
|preg_replace|() - Perform a regular expression search and replace
|strtr|() - Translate characters or replace substrings
User Contributed Notes 11 notes
16 sawdust ¶8 years ago~
Here's a different approach to search result keyword highlighting that
will match all keyword sub strings in a case insensitive manner and
preserve case in the returned text. This solution first grabs all
matches within $haystack in a case insensitive manner, and the
secondly loops through each of those matched sub strings and applies a
case sensitive replace in $haystack. This way each unique (in terms of
case) instance of $needle is operated on individually allowing a case
sensitive replace to be done in order to preserve the original case of
each unique instance of $needle.
>
= 1) {
foreach ($matches[0] as $match) {
$haystack = str_replace($match, ''.$match.' ', $haystack);
}
}
return $haystack;
}
?>
<
6 daevid at daevid dot com ¶11 years ago~
here's a neat little function I whipped up to do HTML color coding of
SQL strings.
>
$1'", $query, -1);
$query = str_ireplace(
array (
'*',
'SELECT ',
'UPDATE ',
'DELETE ',
'INSERT ',
'INTO',
'VALUES',
'FROM',
'LEFT',
'JOIN',
'WHERE',
'LIMIT',
'ORDER BY',
'AND',
'OR ', //[dv] note the space. otherwise you match to 'COLOR' ;-)
'DESC',
'ASC',
'ON '
),
array (
"* ",
"SELECT ",
"UPDATE ",
"DELETE ",
"INSERT ",
"INTO ",
"VALUES ",
"FROM ",
"LEFT ",
"JOIN ",
"WHERE ",
"LIMIT ",
"ORDER BY ",
"AND ",
"OR ",
"DESC ",
"ASC ",
"ON "
),
$query
);
echo "SQL[".$SQL_INT."]: ".$query."; \n";
$SQL_INT++;
} //SQL_DEBUG
?>
<
--------------------------------------------------------------------------------
*str_pad*
+---------+~
| str_pad |~
+---------+~
(PHP 4 >= 4.0.1, PHP 5, PHP 7)
str_pad — Pad a string to a certain length with another string
Description~
>
string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )
<
This functions returns the input string padded on the left, the right,
or both sides to the specified padding length. If the optional
argument pad_string is not supplied, the input is padded with spaces,
otherwise it is padded with characters from pad_string up to the
limit.
Parameters~
input
-----
The input string.
pad_length
----------
If the value of pad_length is negative, less than, or equal to the
length of the input string, no padding takes place, and input will be
returned.
pad_string
Note:
The pad_string may be truncated if the required number of padding characters can't be evenly divided by the pad_string's length.
pad_type
Optional argument pad_type can be STR_PAD_RIGHT, STR_PAD_LEFT, or
STR_PAD_BOTH. If pad_type is not specified it is assumed to be
STR_PAD_RIGHT.
Return Values~
Returns the padded string.
Examples~
Example #1 str_pad() example
>
<
User Contributed Notes 21 notes
35 Marjune ¶2 years ago~
since the default pad_type is STR_PAD_RIGHT. using STR_PAD_BOTH were
always favor in the right pad if the required number of padding
characters can't be evenly divided.
e.g
>
<
15 wes at nospamplsexample dot org ¶2 years ago~
multibyte version:
>
<
8 qeremy [atta] gmail [dotta] com ¶4 years ago~
A proper unicode string padder;
>
<
Test;
>
<
Output;
len 3: ...
len 3: ...
len 4: ...A
len 4: ...Ä
len 5: A...A
len 5: Ä...Ä
len 6: A...AO
len 6: Ä...ÄÖ
...
6 pestilenc at hotmail dot com ¶14 years ago~
For me this worked.
$string = 'help';
#First, str_pad() with unique character.
$string = str_pad($string, 10, "*", STR_PAD_BOTH);
#$string = '***help***';
#Second, str_replace with ' '
$string = str_replace("*", " ", $string);
--------------------------------------------------------------------------------
*str_repeat*
+------------+~
| str_repeat |~
+------------+~
(PHP 4, PHP 5, PHP 7)
str_repeat — Repeat a string
Description~
>
string str_repeat ( string $input , int $multiplier )
<
Returns input repeated multiplier times.
Parameters~
input
-----
The string to be repeated.
multiplier
----------
Number of time the input string should be repeated.
multiplier has to be greater than or equal to 0. If the multiplier is set to 0, the function will return an empty string.
Return Values~
Returns the repeated string.
Examples~
Example #1 str_repeat() example
>
<
The above example will output:
-=-=-=-=-=-=-=-=-=-=
See Also~
for
|str_pad|() - Pad a string to a certain length with another string
|substr_count|() - Count the number of substring occurrences
User Contributed Notes 4 notes
18 Damien Bezborodov ¶7 years ago~
Here is a simple one liner to repeat a string multiple times with a
separator:
>
<
Example script:
>
<
Example Output:
bar,bar,bar,bar,bar
?,?,?
--------------------------------------------------------------------------------
*str_replace*
+-------------+~
| str_replace |~
+-------------+~
(PHP 4, PHP 5, PHP 7)
str_replace — Replace all occurrences of the search string with the
replacement string
Description~
>
mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
<
This function returns a string or an array with all occurrences of
search in subject replaced with the given replace value.
If you don't need fancy replacing rules (like regular expressions),
you should always use this function instead of preg_replace().
Parameters~
If search and replace are arrays, then str_replace() takes a value
from each array and uses them to search and replace on subject. If
replace has fewer values than search, then an empty string is used for
the rest of replacement values. If search is an array and replace is a
string, then this replacement string is used for every value of
search. The converse would not make sense, though.
If search or replace are arrays, their elements are processed first to last.
search
------
The value being searched for, otherwise known as the needle. An array
may be used to designate multiple needles.
replace
-------
The replacement value that replaces found search values. An array may
be used to designate multiple replacements.
subject
-------
The string or array being searched and replaced on, otherwise known as
the haystack.
If subject is an array, then the search and replace is performed with
every entry of subject, and the return value is an array as well.
count
-----
If passed, this will be set to the number of replacements performed.
Return Values~
This function returns a string or an array with the replaced values.
Examples~
Example #1 Basic str_replace() examples
>
$bodytag = str_replace("%body%", "black", "");
// Provides: Hll Wrld f PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
// Provides: You should eat pizza, beer, and ice cream every day
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy = array("pizza", "beer", "ice cream");
$newphrase = str_replace($healthy, $yummy, $phrase);
// Provides: 2
$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count;
?>
<
Example #2 Examples of potential str_replace() gotchas
>
';
// Processes \r\n's first so they aren't converted twice.
$newstr = str_replace($order, $replace, $str);
// Outputs F because A is replaced with B, then B is replaced with C, and so on...
// Finally E is replaced with F, because of left to right replacements.
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);
// Outputs: apearpearle pear
// For the same reason mentioned above
$letters = array('a', 'p');
$fruit = array('apple', 'pear');
$text = 'a p';
$output = str_replace($letters, $fruit, $text);
echo $output;
?>
<
Notes~
Note: This function is binary-safe.
Caution
Replacement order gotcha
Because str_replace() replaces left to right, it might replace a
previously inserted value when doing multiple replacements. See also
the examples in this document.
Note:
This function is case-sensitive. Use str_ireplace() for case-insensitive replace.
See Also~
|str_ireplace|() - Case-insensitive version of str_replace.
|substr_replace|() - Replace text within a portion of a string
|preg_replace|() - Perform a regular expression search and replace
|strtr|() - Translate characters or replace substrings
User Contributed Notes 42 notes
141 nikolaz dot tang at hotmail dot com ¶6 years ago~
A faster way to replace the strings in multidimensional array is to
json_encode() it, do the str_replace() and then json_decode() it, like
this:
>
<
This method is almost 3x faster (in 10000 runs.) than using recursive calling and looping method, and 10x simpler in coding.
Compared to:
>
<
33 Wes Foster ¶7 years ago~
Feel free to optimize this using the while/for or anything else, but
this is a bit of code that allows you to replace strings found in an
associative array.
For example:
>
'cat',
'apple' => 'orange'
'chevy' => 'ford'
);
$string = 'I like to eat an apple with my dog in my chevy';
echo str_replace_assoc($replace,$string);
// Echo: I like to eat an orange with my cat in my ford
?>
<
Here is the function:
>
<
[Jun 1st, 2010 - EDIT BY thiago AT php DOT net: Function has been
replaced with an updated version sent by ljelinek AT gmail DOT com]
23 Alberto Lepe ¶7 years ago~
Be careful when replacing characters (or repeated patterns in the FROM
and TO arrays):
For example:
>
<
I would expect as result: "ZDDB"
However, this return: "ZDDD"
(Because B = D according to our array)
To make this work, use "strtr" instead:
>
"A","2" => "B","3" => "C","B" => "D");
$word = "ZBB2";
echo strtr($word,$arr);
?>
<
This returns: "ZDDB"
10 mrrehbein at gmail dot com ¶1 year ago~
nikolaz dot tang at hotmail dot com's solution of using
json_encode/decode is interesting, but a couple of issues to be aware
of with it.
>
<
json_decode will return objects, where arrays are probably expected.
This is easily remedied by adding 2nd parameter 'true' to json_decode.
$search and $replace could contain strings that match json encoding,
which will either change the structure returned by this method, or
break the json.
ie:
>
'stuff']));
var_dump(str_replace_json('this":"', 'this" : "thing", "with":"', ['this' => 'stuff']));
?>
<
26 moostende at gmail dot com ¶5 years ago~
Note that this does not replace strings that become part of
replacement strings. This may be a problem when you want to remove
multiple instances of the same repetative pattern, several times in a
row.
If you want to remove all dashes but one from the string
'-aaa----b-c-----d--e---f' resulting in '-aaa-b-c-d-e-f', you cannot
use str_replace. Instead, use preg_replace:
>
';
echo preg_replace('/--+/', '-', $challenge).' ';
?>
<
This outputs the following:
-aaa--b-c---d-e--f
-aaa-b-c-d-e-f
10 David Holt ¶1 year ago~
Be aware that if you use this for filtering & sanitizing some form of
user input, or remove ALL instances of a string, there's another
gotcha to watch out for:
// Remove all double characters
$string="1001011010";
$string=str_replace(array("11","00"),"",$string);
// Output: "110010"
$string="ml> Malicious code html> etc";
$string=str_replace(array("",""),"",$string);
// Output: " Malicious code etc"
up
down
13 jay_knows_(all)uk at hotmail dot com ¶6 years ago
This strips out horrible MS word characters.
Just keep fine tuning it until you get what you need, you'll see ive commented some out which caused problems for me.
There could be some that need adding in, but its a start to anyone who wishes to make their own custom function.
>
', $str); // right single guillemet
// $str = str_replace(chr(156), 'oe', $str); // oe ligature
$str = str_replace(chr(159), 'Y', $str); // Y Dieresis
$str = str_replace('°C', '°C', $str); // Celcius is used quite a lot so it makes sense to add this in
$str = str_replace('£', '£', $str);
$str = str_replace("'", "'", $str);
$str = str_replace('"', '"', $str);
$str = str_replace('–', '–', $str);
return $str;
}
?>
<
8 pjcdawkins at googlemail dot com ¶6 years ago~
Here's a deep replace function allowing multi-dimensional arrays in
$search, $replace and $subject. The keys and other structure of
$subject are preserved.
>
<
--------------------------------------------------------------------------------
*str_rot13*
+-----------+~
| str_rot13 |~
+-----------+~
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
str_rot13 — Perform the rot13 transform on a string
Description~
>
string str_rot13 ( string $str )
<
Performs the ROT13 encoding on the str argument and returns the
resulting string.
The ROT13 encoding simply shifts every letter by 13 places in the
alphabet while leaving non-alpha characters untouched. Encoding and
decoding are done by the same function, passing an encoded string as
argument will return the original version.
Parameters~
str
-----
The input string.
Return Values~
Returns the ROT13 version of the given string.
Examples~
Example #1 str_rot13() example
>
<
User Contributed Notes 10 notes
17 shaun ¶5 years ago~
I was reminded again of the desire for a generic str_rot function.
Character manipulation loops in PHP are slow compared to their C
counterparts, so here's a tuned version of the previous function I
posted. It's 1.6 times as fast, mainly by avoiding chr() calls.
>
= 'a' && $c <= 'z') {
$s[$i] = $letters[(ord($c) - 71 + $n) % 26];
} else if ($c >= 'A' && $c <= 'Z') {
$s[$i] = $letters[(ord($c) - 39 + $n) % 26 + 26];
}
}
return $s;
}
?>
<
But using strtr() you can get something 10 times as fast as the above :
>
<
This technique is faster because PHP's strtr is implemented in C using
a byte lookup table (it has O(m + n) complexity). However, PHP 6 will
use Unicode, so I guess(?) strtr will then have to be implemented with
a search for each character (O(m * n)). Using strtr might still be
faster since it offloads the character manipulation to C rather than
PHP, but I don't really know. Take your pick.
Happy coding!
(Benchmark code):
>
<
6 peter at NOSPAM jamit dot com ¶7 years ago~
This ROT13 variant is different from my earlier version in that it
retains 'ethnicity'. For example, a Chinese text when encrypted will
remain Chinese, and the string will not be making sense (the real
meaning will be encrypted). Just look at the code and you will
understand.
>
0; ) {
$array[] = mb_substr($string, 0, 1, $encoding);
$string = mb_substr($string, 1, $strlen, $encoding);
$strlen = $strlen - 1;
}
return $array;
}
function unicodeRotN($str, $offset, $encoding = 'UTF-8') {
$val = '';
$array = mbStringToArray ($str, $encoding = 'UTF-8');
$len = count($array);
for ($i = 0; $i < $len; $i++) {
$val .= ords2unichar(unichar2ords($array[$i], $encoding) + $offset, $encoding);
}
return $val;
}
// example
$original = '??????'; // means "China is my home"
$encrypted = unicodeRotN($string, 13); // ?????? means "Ñ Ai injustice for the Mission Day" (Google translation)
$decrypted = unicodeRotN($encrypted, -13); // ??????
?>
<
--------------------------------------------------------------------------------
*str_shuffle*
+-------------+~
| str_shuffle |~
+-------------+~
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
str_shuffle — Randomly shuffles a string
Description~
>
string str_shuffle ( string $str )
<
str_shuffle() shuffles a string. One permutation of all possible is
created.
Caution
This function does not generate cryptographically secure values, and
should not be used for cryptographic purposes. If you need a
cryptographically secure value, consider using random_int(),
random_bytes(), or openssl_random_pseudo_bytes() instead.
Parameters~
str
-----
The input string.
Return Values~
Returns the shuffled string.
Changelog
Version Description
7.1.0 The internal randomization algorithm has been changed to use
the » Mersenne Twister Random Number Generator instead of the libc
rand function.
Examples~
Example #1 str_shuffle() example
>
<
See Also~
|shuffle|() - Shuffle an array
|rand|() - Generate a random integer
31 jojersztajner at OXYGEN dot POLAND ¶9 years ago~
Aoccdrnig to rseearch at an Elingsh uinervtisy, it deosn't mttaer in
waht oredr the ltteers in a wrod are, the olny iprmoatnt tihng is that
the frist and lsat ltteer is at the rghit pclae. The rset can be a
toatl mses and you can sitll raed it wouthit a porbelm. Tihs is
bcuseae we do not raed ervey lteter by it slef but the wrod as a
wlohe.
Hree's a cdoe taht slerbmcas txet in tihs way:
>
<
It may be ufseul if you wnat to cetare an aessblicce CTCPAHA.
--------------------------------------------------------------------------------
*str_split*
+-----------+~
| str_split |~
+-----------+~
(PHP 5, PHP 7)
str_split — Convert a string to an array
Description~
>
array str_split ( string $string [, int $split_length = 1 ] )
<
Converts a string to an array.
Parameters~
string
------
The input string.
split_length
------------
Maximum length of the chunk.
Return Values~
If the optional split_length parameter is specified, the returned
array will be broken down into chunks with each being split_length in
length, otherwise each chunk will be one character in length.
FALSE is returned if split_length is less than 1. If the split_length
length exceeds the length of string, the entire string is returned as
the first (and only) array element.
Examples~
Example #1 Example uses of str_split()
>
<
The above example will output:
Array
(
[0] => H
[1] => e
[2] => l
[3] => l
[4] => o
[5] =>
[6] => F
[7] => r
[8] => i
[9] => e
[10] => n
[11] => d
)
Array
(
[0] => Hel
[1] => lo
[2] => Fri
[3] => end
)
Notes
Note:
str_split() will split into bytes, rather than characters when dealing
with a multi-byte encoded string.
See Also~
|chunk_split|() - Split a string into smaller chunks
|preg_split|() - Split string by a regular expression
|explode|() - Split a string by string
|count_chars|() - Return information about characters used in a string
|str_word_count|() - Return information about words used in a string
for
User Contributed Notes 38 notes
71 qeremy [atta] gmail [dotta] com ¶5 years ago~
A proper unicode string split;
>
0) {
$ret = array();
$len = mb_strlen($str, "UTF-8");
for ($i = 0; $i < $len; $i += $l) {
$ret[] = mb_substr($str, $i, $l, "UTF-8");
}
return $ret;
}
return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
}
?>
<
$s = "Ilik süt"; // Mild milk
print_r(str_split($s, 3));
print_r(str_split_unicode($s, 3));
Array
(
[0] => Il?
[1] => ?k
[2] => sü
[3] => t
)
Array
(
[0] => Ili
[1] => k s
[2] => üt
)
--------------------------------------------------------------------------------
*str_word_count*
+----------------+~
| str_word_count |~
+----------------+~
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
str_word_count — Return information about words used in a string
Description~
>
mixed str_word_count ( string $string [, int $format = 0 [, string $charlist ]] )
<
Counts the number of words inside string. If the optional format is
not specified, then the return value will be an integer representing
the number of words found. In the event the format is specified, the
return value will be an array, content of which is dependent on the
format. The possible value for the format and the resultant outputs
are listed below.
For the purpose of this function, 'word' is defined as a locale
dependent string containing alphabetic characters, which also may
contain, but not start with "'" and "-" characters.
Parameters~
string
------
The string
format
------
Specify the return value of this function. The current supported
values are:
0 - returns the number of words found
1 - returns an array containing all the words found inside the string
2 - returns an associative array, where the key is the numeric
position of the word inside the string and the value is the actual
word itself charlist
A list of additional characters which will be considered as 'word'
Return Values~
Returns an array or an integer, depending on the format chosen.
Changelog~
Version Description
5.1.0 Added the charlist parameter
Examples~
Example #1 A str_word_count() example
>
<
The above example will output:
Array
(
[0] => Hello
[1] => fri
[2] => nd
[3] => you're
[4] => looking
[5] => good
[6] => today
)
Array
(
[0] => Hello
[6] => fri
[10] => nd
[14] => you're
[29] => looking
[46] => good
[51] => today
)
Array
(
[0] => Hello
[1] => fri3nd
[2] => you're
[3] => looking
[4] => good
[5] => today
)
7
See Also~
|explode|() - Split a string by string
|preg_split|() - Split string by a regular expression
|split|() - Split string into array by regular expression
|count_chars|() - Return information about characters used in a string
|substr_count|() - Count the number of substring occurrences
User Contributed Notes 29 notes
19 cito at wikatu dot com ¶5 years ago~
>
<
9 splogamurugan at gmail dot com ¶8 years ago~
We can also specify a range of values for charlist.
>
<
will give the result as
Array ( [0] => Hello [1] => fri3nd [2] => you're [3] => looking [4] =>
good [5] => today [6] => look123 [7] => ing )
--------------------------------------------------------------------------------
*strcasecmp*
+------------+~
| strcasecmp |~
+------------+~
(PHP 4, PHP 5, PHP 7)
strcasecmp — Binary safe case-insensitive string comparison
Description~
>
int strcasecmp ( string $str1 , string $str2 )
<
Binary safe case-insensitive string comparison.
Parameters~
str1
-----
The first string
str2
-----
The second string
Return Values~
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than
str2, and 0 if they are equal.
Examples~
Example #1 strcasecmp() example
>
<
See Also~
|strcmp|() - Binary safe string comparison
|preg_match|() - Perform a regular expression match
|substr_compare|() - Binary safe comparison of two strings from an offset, up to length characters
|strncasecmp|() - Binary safe case-insensitive string comparison of the first n characters
|stristr|() - Case-insensitive strstr
|substr|() - Return part of a string
User Contributed Notes 3 notes
11 chris at cmbuckley dot co dot uk ¶5 years ago~
A simple multibyte-safe case-insensitive string comparison:
>
<
Caveat: watch out for edge cases like "ß".
10 Anonymous ¶14 years ago~
The sample above is only true on some platforms that only use a simple
'C' locale, where individual bytes are considered as complete
characters that are converted to lowercase before being
differentiated.
Other locales (see LC_COLLATE and LC_ALL) use the difference of
collation order of characters, where characters may be groups of bytes
taken from the input strings, or simply return -1, 0, or 1 as the
collation order is not simply defined by comparing individual
characters but by more complex rules.
Don't base your code on a specific non null value returned by strcmp()
or strcasecmp(): it is not portable. Just consider the sign of the
result and be sure to use the correct locale!
8 alvaro at demogracia dot com ¶6 years ago~
Don't forget this is a single-byte function: in Unicode strings it'll
provide incoherent results as soon as both strings differ only in
case. There doesn't seem to exist a built-in multi-byte alternative so
you need to write your own, taking into account both character
encoding and collation.
--------------------------------------------------------------------------------
*strchr*
+--------+~
| strchr |~
+--------+~
(PHP 4, PHP 5, PHP 7)
strchr — Alias of strstr()
Description~
This function is an alias of: strstr().
User Contributed Notes 2 notes
6 webmaster at lyndonstate dot edu ¶13 years ago~
Alternative Way:
To get all the text before the first occurence.
-----------------------------------------------
INCLUDING A NEEDLE:
$string1 = "I need cookies & soda.";
$needle = "cookies";
//find length of the needle
$needle_len = strlen($needle);
//find postion
$position_num = strpos($string1,$needle) + $needle_len;
//cut the string
$result_string = substr("$string1",0,$position_num);
//display it
echo"$result_string"; // I need cookies
-----------------------------------------------
SHORTER VERSION:
$result_string = substr("$string1",0,strpos($string1,$needle)+strlen($needle));
echo"$result_string";//I need cookies
-----------------------------------------------
EXCLUDING THE NEEDLE:
$result_string = substr("$string1",0,strpos($string1,$needle));
echo"$result_string";// I need
-----------------------------------------------
FREE EMAIL JUNK?
This is probably useful for processing emails.
For example, someone sends email to your server from Yahoo account.
Free email always comes with wasted stuff like...
"Do you Yahoo!? The New Yahoo! Shopping - with improved product search ".
We can delete the phrase like this:
$needle="Do you Yahoo!?";
$result_string = substr("$emailstring",0,strpos($emailstring, $needle));
--------------------------------------------------------------------------------
*strcmp*
+--------+~
| strcmp |~
+--------+~
(PHP 4, PHP 5, PHP 7)
strcmp — Binary safe string comparison
Description~
>
int strcmp ( string $str1 , string $str2 )
<
Note that this comparison is case sensitive.
Parameters~
str1
-----
The first string.
str2
-----
The second string.
Return Values~
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than
str2, and 0 if they are equal.
Examples~
Example #1 strcmp() example
>
<
See Also~
|strcasecmp|() - Binary safe case-insensitive string comparison
|preg_match|() - Perform a regular expression match
|substr_compare|() - Binary safe comparison of two strings from an offset, up to length characters
|strncmp|() - Binary safe string comparison of the first n characters
|strstr|() - Find the first occurrence of a string
|substr|() - Return part of a string
User Contributed Notes 23 notes
43 jendoj at gmail dot com ¶4 years ago~
If you rely on strcmp for safe string comparisons, both parameters
must be strings, the result is otherwise extremely unpredictable. For
instance you may get an unexpected 0, or return values of NULL, -2, 2,
3 and -3.
strcmp("5", 5) => 0
strcmp("15", 0xf) => 0
strcmp(61529519452809720693702583126814, 61529519452809720000000000000000) => 0
strcmp(NULL, false) => 0
strcmp(NULL, "") => 0
strcmp(NULL, 0) => -1
strcmp(false, -1) => -2
strcmp("15", NULL) => 2
strcmp(NULL, "foo") => -3
strcmp("foo", NULL) => 3
strcmp("foo", false) => 3
strcmp("foo", 0) => 1
strcmp("foo", 5) => 1
strcmp("foo", array()) => NULL + PHP Warning
strcmp("foo", new stdClass) => NULL + PHP Warning
strcmp(function(){}, "") => NULL + PHP Warning
22 Rob Wiesler ¶7 years ago~
One big caveat - strings retrieved from the backtick operation may be
zero terminated (C-style), and therefore will not be equal to the
non-zero terminated strings (roughly Pascal-style) normal in PHP. The
workaround is to surround every `` pair or shell_exec() function with
the trim() function. This is likely to be an issue with other
functions that invoke shells; I haven't bothered to check.
On Debian Lenny (and RHEL 5, with minor differences), I get this:
====PHP====
>
sz = ".$sz." str_split(sz) = "; print_r(str_split($sz));
echo " ";
echo "Pascal-style string: ps = ".$ps." str_split(ps) = "; print_r(str_split($ps));
echo " ";
echo "Normal results of comparison: ";
echo "sz == ps = ".($sz == $ps ? "true" : "false")." ";
echo "strcmp(sz,ps) = ".strcmp($sz,$ps);
echo " ";
echo "Comparison with trim()'d zero-terminated string: ";
echo "trim(sz) = ".trim($sz)." ";
echo "str_split(trim(sz)) = "; print_r(str_split(trim($sz))); echo " ";
echo "trim(sz) == ps = ".(trim($sz) == $ps ? "true" : "false")." ";
echo "strcmp(trim(sz),ps) = ".strcmp(trim($sz),$ps);
?>
<
====Output====
Zero-terminated string:
sz = /var/www
str_split(sz) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w [8] => )
Pascal-style string:
ps = /var/www
str_split(ps) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w )
Normal results of comparison:
sz == ps = false
strcmp(sz,ps) = 1
Comparison with trim()'d zero-terminated string:
trim(sz) = /var/www
str_split(trim(sz)) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w )
trim(sz) == ps = true
strcmp(trim(sz),ps) = 0
22 lehal2 at hotmail dot com ¶4 years ago~
i hope this will give you a clear idea how strcmp works internally.
>
";
$str2 = "t";
echo ord($str2); //116
echo " ";
echo ord($str1)-ord($str2);//-18
$str1 = "bear";
$str2 = "tear";
$str3 = "";
echo "";
echo strcmp($str1, $str2); // -18
echo " ";
echo strcmp($str2, $str1); //18
echo " ";
echo strcmp($str2, $str2); //0
echo " ";
echo strcmp($str2, $str3); //4
echo " ";
echo strcmp($str3, $str2); //-4
echo " ";
echo strcmp($str3, $str3); // 0
echo " ";
?>
<
10 frewuill at merlin-corp dot com ¶17 years ago~
Hey be sure the string you are comparing has not special characters
like '\n' or something like that.
7 hm2k at php dot net ¶6 years ago~
Don't forget the similar_text() function...
http://php.net/manual/en/function.similar-text.php
6 hrodicus at gmail dot com ¶6 years ago~
Note a difference between 5.2 and 5.3 versions
echo (int)strcmp('pending',array());
will output -1 in PHP 5.2.16 (probably in all versions prior 5.3)
but will output 0 in PHP 5.3.3
Of course, you never need to use array as a parameter in string comparisions.
--------------------------------------------------------------------------------
*strcoll*
+---------+~
| strcoll |~
+---------+~
(PHP 4 >= 4.0.5, PHP 5, PHP 7)
strcoll — Locale based string comparison
Description~
>
int strcoll ( string $str1 , string $str2 )
<
Note that this comparison is case sensitive, and unlike strcmp() this
function is not binary safe.
strcoll() uses the current locale for doing the comparisons. If the
current locale is C or POSIX, this function is equivalent to strcmp().
Parameters~
str1
-----
The first string.
str2
-----
The second string.
Return Values~
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than
str2, and 0 if they are equal.
Changelog~
Version Description
4.2.3 This function now works on win32.
See Also~
|preg_match|() - Perform a regular expression match
|strcmp|() - Binary safe string comparison
|strcasecmp|() - Binary safe case-insensitive string comparison
|substr|() - Return part of a string
|stristr|() - Case-insensitive strstr
|strncasecmp|() - Binary safe case-insensitive string comparison of the first n characters
|strncmp|() - Binary safe string comparison of the first n characters
|strstr|() - Find the first occurrence of a string
|setlocale|() - Set locale information
--------------------------------------------------------------------------------
*strcspn*
+---------+~
| strcspn |~
+---------+~
(PHP 4, PHP 5, PHP 7)
strcspn — Find length of initial segment not matching mask
Description~
>
int strcspn ( string $subject , string $mask [, int $start [, int $length ]] )
<
Returns the length of the initial segment of subject which does not
contain any of the characters in mask.
If start and length are omitted, then all of subject will be examined.
If they are included, then the effect will be the same as calling
strcspn(substr($subject, $start, $length), $mask) (see substr for more
information).
Parameters~
subject
-------
The string to examine.
mask
-----
The string containing every disallowed character.
start
-----
The position in subject to start searching.
If start is given and is non-negative, then strcspn() will begin
examining subject at the start'th position. For instance, in the
string 'abcdef', the character at position 0 is 'a', the character at
position 2 is 'c', and so forth.
If start is given and is negative, then strcspn() will begin examining
subject at the start'th position from the end of subject.
length
------
The length of the segment from subject to examine.
If length is given and is non-negative, then subject will be examined
for length characters after the starting position.
If length is given and is negative, then subject will be examined from
the starting position up to length characters from the end of subject.
Return Values
Returns the length of the initial segment of subject which consists
entirely of characters not in mask.
Note:
When a start parameter is set, the returned length is counted starting
from this position, not from the beginning of subject.
Examples~
Example #1 strcspn() example
>
<
The above example will output:
int(0)
int(0)
int(2)
int(2)
int(5)
int(4)
Notes
Note: This function is binary-safe.
See Also~
|strspn|() - Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask.
--------------------------------------------------------------------------------
*strip_tags*
+------------+~
| strip_tags |~
+------------+~
(PHP 4, PHP 5, PHP 7)
strip_tags — Strip HTML and PHP tags from a string
Description~
>
string strip_tags ( string $str [, string $allowable_tags ] )
<
This function tries to return a string with all NULL bytes, HTML and
PHP tags stripped from a given str. It uses the same tag stripping
state machine as the fgetss() function.
Parameters~
str
-----
The input string.
allowable_tags
--------------
You can use the optional second parameter to specify tags which should
not be stripped.
Note:
HTML comments and PHP tags are also stripped. This is hardcoded and
can not be changed with allowable_tags.
Note:
In PHP 5.3.4 and later, self-closing XHTML tags are ignored and only
non-self-closing tags should be used in allowable_tags. For example,
to allow both and , you should use:
>
');
?>
<
Return Values~
Returns the stripped string.
Changelog~
Version Description
5.3.4 strip_tags() ignores self-closing XHTML tags in allowable_tags.
5.0.0 strip_tags() is now binary safe.
Examples~
Example #1 strip_tags() example
>
Test paragraph. Other text ';
echo strip_tags($text);
echo "\n";
// Allow and
echo strip_tags($text, '');
?>
<
The above example will output:
Test paragraph. Other text
Test paragraph.
Other text
Notes~
Warning
Because strip_tags() does not actually validate the HTML, partial or
broken tags can result in the removal of more text/data than expected.
Warning
This function does not modify any attributes on the tags that you
allow using allowable_tags, including the style and onmouseover
attributes that a mischievous user may abuse when posting text that
will be shown to other users.
Note:
Tag names within the input HTML that are greater than 1023 bytes in
length will be treated as though they are invalid, regardless of the
allowable_tags parameter.
See Also~
|htmlspecialchars|() - Convert special characters to HTML entities
User Contributed Notes 13 notes
100 mariusz.tarnaski at wp dot pl ¶8 years ago~
Hi. I made a function that removes the HTML tags along with their contents:
Function:
>
/si', trim($tags), $tags);
$tags = array_unique($tags[1]);
if(is_array($tags) AND count($tags) > 0) {
if($invert == FALSE) {
return preg_replace('@<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?\1>@si', '', $text);
}
else {
return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?\1>@si', '', $text);
}
}
elseif($invert == FALSE) {
return preg_replace('@<(\w+)\b.*?>.*?\1>@si', '', $text);
}
return $text;
}
?>
<
Sample text:
$text = 'sample text with
tags
';
Result for strip_tags($text):
sample text with tags
Result for strip_tags_content($text):
text with
Result for strip_tags_content($text, ''):
sample text with
Result for strip_tags_content($text, '', TRUE);
text with tags
I hope that someone is useful :)
43 CEO at CarPool2Camp dot org ¶8 years ago~
Note the different outputs from different versions of the same tag:
>
Each New Line';
$new = strip_tags($data, ' ');
var_dump($new); // OUTPUTS string(21) " EachNew Line"
Each New Line';
$new = strip_tags($data, ' ');
var_dump($new); // OUTPUTS string(16) "Each NewLine"
Each New Line';
$new = strip_tags($data, ' ');
var_dump($new); // OUTPUTS string(11) "EachNewLine"
?>
<
11 Trititaty ¶1 year ago~
Features:
* allowable tags (as in strip_tags),
* optional stripping attributes of the allowable tags,
* optional comment preserving,
* deleting broken and unclosed tags and comments,
* optional callback function call for every piece processed allowing for flexible replacements.
>
|^)\\s*(?:<|$)/', $allowable_tags, -1, PREG_SPLIT_NO_EMPTY ), // get tag names
function( $tag ) { return preg_match( '/^[a-z][a-z0-9_]*$/i', $tag ); } // filter broken
) );
$comments_and_stuff = preg_split( '/(|$))/', $str, -1, PREG_SPLIT_DELIM_CAPTURE );
foreach ( $comments_and_stuff as $i => $comment_or_stuff ) {
if ( $i % 2 ) { // html comment
if ( !( $preserve_comments && preg_match( '//', $comment_or_stuff ) ) ) {
$comments_and_stuff[$i] = '';
}
} else { // stuff between comments
$tags_and_text = preg_split( "/(<(?:[^>\"']++|\"[^\"]*+(?:\"|$)|'[^']*+(?:'|$))*(?:>|$))/", $comment_or_stuff, -1, PREG_SPLIT_DELIM_CAPTURE );
foreach ( $tags_and_text as $j => $tag_or_text ) {
$is_broken = false;
$is_allowable = true;
$result = $tag_or_text;
if ( $j % 2 ) { // tag
if ( preg_match( "%^(?)([a-z][a-z0-9_]*)\\b(?:[^>\"'/]++|/+?|\"[^\"]*\"|'[^']*')*?(/?>)%i", $tag_or_text, $matches ) ) {
$tag = strtolower( $matches[2] );
if ( in_array( $tag, $allowable_tags ) ) {
if ( $strip_attrs ) {
$opening = $matches[1];
$closing = ( $opening === '' ) ? '>' : $closing;
$result = $opening . $tag . $closing;
}
} else {
$is_allowable = false;
$result = '';
}
} else {
$is_broken = true;
$result = '';
}
} else { // text
$tag = false;
}
if ( !$is_broken && isset( $callback ) ) {
// allow result modification
call_user_func_array( $callback, array( &$result, $tag_or_text, $tag, $is_allowable ) );
}
$tags_and_text[$j] = $result;
}
$comments_and_stuff[$i] = implode( '', $tags_and_text );
}
}
$str = implode( '', $comments_and_stuff );
return $str;
}
?>
<
Callback arguments:
* &$result: contains text to be placed insted of original piece (e.g. empty string for forbidden tags), it can be changed;
* $tag_or_text: original piece of text or a tag (see below);
* $tag: false for text between tags, lowercase tag name for tags;
* $is_allowable: boolean telling if a tag isn't allowed (to avoid double checking), always true for text between tags
*
Callback function isn't called for comments and broken tags.
Caution: the function doesn't fully validate tags (the more so HTML
itself), it just force strips those obviously broken (in addition to
stripping forbidden tags). If you want to get valid tags then use
strip_attrs option, though it doesn't guarantee tags are balanced or
used in the appropriate context. For complex logic consider using DOM
parser.
9 doug at exploittheweb dot com ¶1 year ago "5.3.4 strip_tags() no
longer strips self-closing XHTML tags unless the self-closing XHTML
tag is also given in allowable_tags."
This is poorly worded.
The above seems to be saying that, since 5.3.4, if you don't specify
" " in allowable_tags then " " will not be stripped... but
that's not actually what they're trying to say.
What it means is, in versions prior to 5.3.4, it "strips self-closing
XHTML tags unless the self-closing XHTML tag is also given in
allowable_tags", and that since 5.3.4 this is no longer the case.
So what reads as "no longer strips self-closing tags (unless the
self-closing XHTML tag is also given in allowable_tags)" is actually
saying "no longer (strips self-closing tags unless the self-closing
XHTML tag is also given in allowable_tags)".
i.e.
pre-5.3.4: strip_tags('Hello World ',' ') => 'Hello
World ' // strips because it wasn't explicitly specified in
allowable_tags
5.3.4 and later: strip_tags('Hello World ',' ') => 'Hello
World ' // does not strip because PHP matches it with
in allowable_tags
21 bzplan at web dot de ¶4 years ago~
a HTML code like this:
>
color is blue
size is huge
material is wood
';
?>
<
with
... the result is:
$str = 'color is bluesize is huge
material is wood';
notice: the words 'blue' and 'size' grow together :(
and line-breaks are still in new string $str
if you need a space between the words (and without line-break)
use my function:
... the result is:
$str = 'color is blue size is huge material is wood';
the function:
>
]*>/', ' ', $string);
// ----- remove control characters -----
$string = str_replace("\r", '', $string); // --- replace with empty space
$string = str_replace("\n", ' ', $string); // --- replace with space
$string = str_replace("\t", ' ', $string); // --- replace with space
// ----- remove multiple spaces -----
$string = trim(preg_replace('/ {2,}/', ' ', $string));
return $string;
}
// --------------------------------------------------------------
?>
<
the KEY is the regex pattern: '/<[^>]*>/'
instead of strip_tags()
... then remove control characters and multiple spaces
:)
--------------------------------------------------------------------------------
*stripcslashes*
+---------------+~
| stripcslashes |~
+---------------+~
(PHP 4, PHP 5, PHP 7)
stripcslashes — Un-quote string quoted with addcslashes()
Description~
>
string stripcslashes ( string $str )
<
Returns a string with backslashes stripped off. Recognizes C-like \n,
\r ..., octal and hexadecimal representation.
Parameters~
str
-----
The string to be unescaped.
Return Values~
Returns the unescaped string.
See Also~
|addcslashes|() - Quote string with slashes in a C style
--------------------------------------------------------------------------------
*stripos*
+---------+~
| stripos |~
+---------+~
(PHP 5, PHP 7)
stripos — Find the position of the first occurrence of a
case-insensitive substring in a string
Description~
>
mixed stripos ( string $haystack , string $needle [, int $offset = 0 ] )
<
Find the numeric position of the first occurrence of needle in the haystack string.
Unlike the strpos(), stripos() is case-insensitive.
Parameters~
haystack
--------
The string to search in.
needle
------
Note that the needle may be a string of one or more characters.
If needle is not a string, it is converted to an integer and applied
as the ordinal value of a character.
offset
------
If specified, search will start this number of characters counted from
the beginning of the string. If the offset is negative, the search
will start this number of characters counted from the end of the
string.
Return Values~
Returns the position of where the needle exists relative to the
beginnning of the haystack string (independent of offset). Also note
that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
Warning
This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
Changelog~
Version Description
7.1.0 Support for negative offsets has been added.
Examples~
Example #1 stripos() examples
>
<
Notes
Note: This function is binary-safe.
See Also~
|mb_stripos|() - Finds position of first occurrence of a string within another, case insensitive
|strpos|() - Find the position of the first occurrence of a substring in a string
|strrpos|() - Find the position of the last occurrence of a substring in a string
|strripos|() - Find the position of the last occurrence of a case-insensitive substring in a string
|stristr|() - Case-insensitive strstr
|substr|() - Return part of a string
|str_ireplace|() - Case-insensitive version of str_replace.
User Contributed Notes 6 notes
21 emperorshishire at gmail dot com ¶8 years ago~
I found myself needing to find the first position of multiple needles
in one haystack. So I wrote this little function:
>
int(16)
["dog"]=>
int(40)
["."]=>
int(43)
["duck"]=>
bool(false)
}
*/
?>
<
7 spam at kleppinger dot com ¶2 years ago~
Regarding the function by spam at wikicms dot org
It is very bad practice to use the same function name as an existing
php function but have a different output format. Someone maintaining
the code in the future is likely to be very confused by this. It will
also be hard to eradicate from a codebase because the naming is
identical so each use of stripos() would have to be analyzed to see
how it is expecting the output format (bool or number/bool).
Calling it string_found() or something like that would make a lot more
sense for long-term use.
--------------------------------------------------------------------------------
*stripslashes*
+--------------+~
| stripslashes |~
+--------------+~
(PHP 4, PHP 5, PHP 7)
stripslashes — Un-quotes a quoted string
Description~
>
string stripslashes ( string $str )
<
Un-quotes a quoted string.
Note:
If magic_quotes_sybase is on, no backslashes are stripped off but two
apostrophes are replaced by one instead. An example use of
stripslashes() is when the PHP directive magic_quotes_gpc is on (it
was on by default before PHP 5.4), and you aren't inserting this data
into a place (such as a database) that requires escaping. For example,
if you're simply outputting data straight from an HTML form.
Parameters~
str
-----
The input string.
Return Values~
Returns a string with backslashes stripped off. (\' becomes ' and so
on.) Double backslashes (\\) are made into a single backslash (\).
Examples~
Example #1 A stripslashes() example
>
<
Note:
stripslashes() is not recursive. If you want to apply this function to
a multi-dimensional array, you need to use a recursive function.
Example #2 Using stripslashes() on an array
>
<
The above example will output:
Array
(
[0] => f'oo
[1] => b'ar
[2] => Array
(
[0] => fo'o
[1] => b'ar
)
)
See Also~
|addslashes|() - Quote string with slashes
|get_magic_quotes_gpc|() - Gets the current configuration setting of magic_quotes_gpc
User Contributed Notes 30 notes
47 ivijan dot stefan at gmail dot com ¶3 years ago~
Sometimes for some reason is happens that PHP or Javascript or some
naughty insert a lot of backslash. Ordinary function does not notice
that. Therefore, it is necessary that the bit "inflate":
>
<
RESULT: My dog don't like the postman!
This flick has served me wery well, because I had this problem before.
--------------------------------------------------------------------------------
*stristr*
+---------+~
| stristr |~
+---------+~
(PHP 4, PHP 5, PHP 7)
stristr — Case-insensitive strstr()
Description~
>
string stristr ( string $haystack , mixed $needle [, bool $before_needle = false ] )
<
Returns all of haystack starting from and including the first
occurrence of needle to the end.
Parameters~
haystack
--------
The string to search in
needle
------
If needle is not a string, it is converted to an integer and applied
as the ordinal value of a character.
before_needle
-------------
If TRUE, stristr() returns the part of the haystack before the first
occurrence of the needle (excluding needle).
needle and haystack are examined in a case-insensitive manner.
Return Values~
Returns the matched substring. If needle is not found, returns FALSE.
Changelog~
Version Description
5.3.0 Added the optional parameter before_needle.
4.3.0 stristr() was made binary safe.
Examples~
Example #1 stristr() example
>
<
Example #2 Testing if a string is found or not
>
<
Example #3 Using a non "string" needle
>
<
Notes
Note: This function is binary-safe.
See Also~
|strstr|() - Find the first occurrence of a string
|strrchr|() - Find the last occurrence of a character in a string
|stripos|() - Find the position of the first occurrence of a case-insensitive substring in a string
|strpbrk|() - Search a string for any of a set of characters
|preg_match|() - Perform a regular expression match
User Contributed Notes 8 notes
12 dpatton.at.confluence.org ¶14 years ago~
There was a change in PHP 4.2.3 that can cause a warning message to be
generated when using stristr(), even though no message was
generated in older versions of PHP.
The following will generate a warning message in 4.0.6 and 4.2.3:
stristr("haystack", "");
OR
$needle = ""; stristr("haystack", $needle);
This will _not_ generate an "Empty Delimiter" warning message in
4.0.6, but _will_ in 4.2.3:
unset($needle); stristr("haystack", $needle);
Here's a URL that documents what was changed:
http://groups.google.ca/groups?selm=cvshholzgra1031224321%40cvsserver
--------------------------------------------------------------------------------
*strlen*
+--------+~
| strlen |~
+--------+~
(PHP 4, PHP 5, PHP 7)
strlen — Get string length
Description~
>
int strlen ( string $string )
<
Returns the length of the given string.
Parameters~
string
------
The string being measured for length.
Return Values~
The length of the string on success, and 0 if the string is empty.
Changelog~
Version Description
5.3.0 Prior versions treated arrays as the string Array, thus
returning a string length of 5 and emitting an E_NOTICE level error.
Examples
Example #1 A strlen() example
>
<
Notes
Note:
strlen() returns the number of bytes rather than the number of
characters in a string.
Note:
strlen() returns NULL when executed on arrays, and an E_WARNING level
error is emitted.
See Also~
|count|() - Count all elements in an array, or something in an object
|grapheme_strlen|() - Get string length in grapheme units
|iconv_strlen|() - Returns the character count of string
|mb_strlen|() - Get string length
User Contributed Notes 15 notes
85 chernyshevsky at hotmail dot com ¶12 years ago~
The easiest way to determine the character count of a UTF8 string is
to pass the text through utf8_decode() first:
>
<
utf8_decode() converts characters that are not in ISO-8859-1 to '?',
which, for the purpose of counting, is quite alright.
30 rm dot nasir at hotmail dot com ¶1 year ago~
I want to share something seriously important for newbies or beginners
of PHP who plays with strings of UTF8 encoded characters or the
languages like: Arabic, Persian, Pashto, Dari, Chinese (simplified),
Chinese (traditional), Japanese, Vietnamese, Urdu, Macedonian,
Lithuanian, and etc. As the manual says: "strlen() returns the number
of bytes rather than the number of characters in a string.", so if you
want to get the number of characters in a string of UTF8 so use
mb_strlen() instead of strlen().
Example:
>
";
var_export( mb_strlen($utf8, 'utf8') ); // 32
?>
<
6 joeri at sebrechts dot net ¶8 months ago~
When checking for length to make sure a value will fit in a database
field, be mindful of using the right function.
There are three possible situations:
1. Most likely case: the database column is UTF-8 with a length
defined in unicode code points (e.g. mysql varchar(200) for a utf-8
database).
>
<
2. The database column has a length defined in bytes (e.g. oracle's VARCHAR2(200 BYTE))
>
<
3. The database column is in another character set (UTF-16,
ISO-8859-1, etc...) with a length defined in characters / code points.
Find the character set used, and pass it explicitly to the length function.
>
<
26 vcardillo at gmail dot com ¶4 years ago~
I would like to demonstrate that you need more than just this function
in order to truly test for an empty string. The reason being that
will return 0. So how do you know if the value
was null, or truly an empty string?
>
";
echo "Length: $len ";
echo "Length: " . strlen(null) . " ";
if (strlen($foo) === 0) echo 'Null length is Zero ';
if ($len === 0) echo 'Null length is still Zero ';
if (strlen($foo) == 0 && !is_null($foo)) echo '!is_null(): $foo is truly an empty string ';
else echo '!is_null(): $foo is probably null ';
if (strlen($foo) == 0 && isset($foo)) echo 'isset(): $foo is truly an empty string ';
else echo 'isset(): $foo is probably null ';
if (strlen($bar) == 0 && !is_null($bar)) echo '!is_null(): $bar is truly an empty string ';
else echo '!is_null(): $foo is probably null ';
if (strlen($bar) == 0 && isset($bar)) echo 'isset(): $bar is truly an empty string ';
else echo 'isset(): $foo is probably null ';
?>
<
// Begin Output:
Length: 0
Length: 0
Length: 0
Null length is Zero
Null length is still Zero
!is_null(): $foo is probably null
isset(): $foo is probably null
!is_null(): $bar is truly an empty string
isset(): $bar is truly an empty string
// End Output
So it would seem you need either is_null() or isset() in addition to strlen() if you care whether or not the original value was null.
--------------------------------------------------------------------------------
*strnatcasecmp*
+---------------+~
| strnatcasecmp |~
+---------------+~
(PHP 4, PHP 5, PHP 7)
strnatcasecmp — Case insensitive string comparisons using a "natural order" algorithm
Description~
>
int strnatcasecmp ( string $str1 , string $str2 )
<
This function implements a comparison algorithm that orders
alphanumeric strings in the way a human being would. The behaviour of
this function is similar to strnatcmp(), except that the comparison is
not case sensitive. For more information see: Martin Pool's » Natural
Order String Comparison page.
Parameters~
str1
-----
The first string.
str2
-----
The second string.
Return Values~
Similar to other string comparison functions, this one returns < 0 if
str1 is less than str2 > 0 if str1 is greater than str2, and 0 if they
are equal.
See Also~
|preg_match|() - Perform a regular expression match
|strcmp|() - Binary safe string comparison
|strcasecmp|() - Binary safe case-insensitive string comparison
|substr|() - Return part of a string
|stristr|() - Case-insensitive strstr
|strncasecmp|() - Binary safe case-insensitive string comparison of the first n characters
|strncmp|() - Binary safe string comparison of the first n characters
|strstr|() - Find the first occurrence of a string
|setlocale|() - Set locale information
User Contributed Notes 3 notes
6 chatfielddaniel at googlemail dot com ¶5 years ago~
The function treats '_' as after letters and numbers when it would be
placed before logically.
--------------------------------------------------------------------------------
*strnatcmp*
+-----------+~
| strnatcmp |~
+-----------+~
(PHP 4, PHP 5, PHP 7)
strnatcmp — String comparisons using a "natural order" algorithm
Description~
>
int strnatcmp ( string $str1 , string $str2 )
<
This function implements a comparison algorithm that orders
alphanumeric strings in the way a human being would, this is described
as a "natural ordering". Note that this comparison is case sensitive.
Parameters~
str1
-----
The first string.
str2
-----
The second string.
Return Values~
Similar to other string comparison functions, this one returns < 0 if
str1 is less than str2; > 0 if str1 is greater than str2, and 0 if
they are equal.
Examples~
An example of the difference between this algorithm and the regular computer string sorting algorithms (used in strcmp()) can be seen below:
>
<
The above example will output:
Standard string comparison
Array
(
[0] => img1.png
[1] => img10.png
[2] => img12.png
[3] => img2.png
)
Natural order string comparison
Array
(
[0] => img1.png
[1] => img2.png
[2] => img10.png
[3] => img12.png
)
For more information see: Martin Pool's » Natural Order String Comparison page.
See Also~
|preg_match|() - Perform a regular expression match
|strcasecmp|() - Binary safe case-insensitive string comparison
|substr|() - Return part of a string
|stristr|() - Case-insensitive strstr
|strcmp|() - Binary safe string comparison
|strncmp|() - Binary safe string comparison of the first n characters
|strncasecmp|() - Binary safe case-insensitive string comparison of the first n characters
|strnatcasecmp|() - Case insensitive string comparisons using a "natural order" algorithm
|strstr|() - Find the first occurrence of a string
|natsort|() - Sort an array using a "natural order" algorithm
|natcasesort|() - Sort an array using a case insensitive "natural order" algorithm
--------------------------------------------------------------------------------
*strncasecmp*
+-------------+~
| strncasecmp |~
+-------------+~
(PHP 4 >= 4.0.2, PHP 5, PHP 7)
strncasecmp — Binary safe case-insensitive string comparison of the
first n characters
Description~
>
int strncasecmp ( string $str1 , string $str2 , int $len )
<
This function is similar to strcasecmp(), with the difference that you
can specify the (upper limit of the) number of characters from each
string to be used in the comparison.
Parameters~
str1
-----
The first string.
str2
-----
The second string.
len
-----
The length of strings to be used in the comparison.
Return Values
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than
str2, and 0 if they are equal.
See Also~
|strncmp|() - Binary safe string comparison of the first n characters
|preg_match|() - Perform a regular expression match
|substr_compare|() - Binary safe comparison of two strings from an offset, up to length characters
|strcasecmp|() - Binary safe case-insensitive string comparison
|stristr|() - Case-insensitive strstr
|substr|() - Return part of a string
--------------------------------------------------------------------------------
*strncmp*
+---------+~
| strncmp |~
+---------+~
(PHP 4, PHP 5, PHP 7)
strncmp — Binary safe string comparison of the first n characters
Description~
>
int strncmp ( string $str1 , string $str2 , int $len )
<
This function is similar to strcmp(), with the difference that you can
specify the (upper limit of the) number of characters from each string
to be used in the comparison.
Note that this comparison is case sensitive.
Parameters~
str1
-----
The first string.
str2
-----
The second string.
len
-----
Number of characters to use in the comparison.
Return Values~
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than
str2, and 0 if they are equal.
See Also~
|strncasecmp|() - Binary safe case-insensitive string comparison of the first n characters
|preg_match|() - Perform a regular expression match
|substr_compare|() - Binary safe comparison of two strings from an offset, up to length characters
|strcmp|() - Binary safe string comparison
|strstr|() - Find the first occurrence of a string
|substr|() - Return part of a string
User Contributed Notes 4 notes
10 elloromtz at gmail dot com ¶6 years ago~
if length is 0 regardless what the two strings are, it will return 0
>
<
--------------------------------------------------------------------------------
*strpbrk*
+---------+~
| strpbrk |~
+---------+~
(PHP 5, PHP 7)
strpbrk — Search a string for any of a set of characters
Description~
>
string strpbrk ( string $haystack , string $char_list )
<
strpbrk() searches the haystack string for a char_list.
Parameters~
haystack
--------
The string where char_list is looked for.
char_list
---------
This parameter is case sensitive.
Return Values~
Returns a string starting from the character found, or FALSE if it is
not found.
Examples~
Example #1 strpbrk() example
>
<
See Also~
|strpos|() - Find the position of the first occurrence of a substring in a string
|strstr|() - Find the first occurrence of a string
|preg_match|() - Perform a regular expression match
User Contributed Notes 2 notes
8 devnuhl ¶2 years ago~
If you're not looking to duplicate the rest of the string, but instead
just want the offset, in the spirit of the str*pos() functions, use
strcspn()
--------------------------------------------------------------------------------
*strpos*
+--------+~
| strpos |~
+--------+~
(PHP 4, PHP 5, PHP 7)
strpos — Find the position of the first occurrence of a substring in a string
Description~
>
mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
<
Find the numeric position of the first occurrence of needle in the
haystack string.
Parameters~
haystack
--------
The string to search in.
needle
------
If needle is not a string, it is converted to an integer and applied
as the ordinal value of a character.
offset
------
If specified, search will start this number of characters counted from
the beginning of the string. If the offset is negative, the search
will start this number of characters counted from the end of the
string.
Return Values~
Returns the position of where the needle exists relative to the
beginning of the haystack string (independent of offset). Also note
that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
Warning
This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
Changelog~
Version Description
7.1.0 Support for negative offsets has been added.
Examples~
Example #1 Using ===
>
<
Example #2 Using !==
>
<
Example #3 Using an offset
>
<
Notes~
Note: This function is binary-safe.
See Also~
|stripos|() - Find the position of the first occurrence of a case-insensitive substring in a string
|strrpos|() - Find the position of the last occurrence of a substring in a string
|strripos|() - Find the position of the last occurrence of a case-insensitive substring in a string
|strstr|() - Find the first occurrence of a string
|strpbrk|() - Search a string for any of a set of characters
|substr|() - Return part of a string
|preg_match|() - Perform a regular expression match
User Contributed Notes 47 notes
98 Suggested re-write for pink WARNING box ¶9 years ago~
WARNING
As strpos may return either FALSE (substring absent) or 0 (substring
at start of string), strict versus loose equivalency operators must be
used very carefully.
To know that a substring is absent, you must use:
=== FALSE
To know that a substring is present (in any position including 0), you
can use either of:
!== FALSE (recommended)
> -1 (note: or greater than any negative number)
To know that a substring is at the start of the string, you must use:
=== 0
To know that a substring is in any position other than the start, you can use any of:
> 0 (recommended)
!= 0 (note: but not !== 0 which also equates to FALSE)
!= FALSE (disrecommended as highly confusing)
Also note that you cannot compare a value of "" to the returned value
of strpos. With a loose equivalence operator (== or !=) it will return
results which don't distinguish between the substring's presence
versus position. With a strict equivalence operator (=== or !==) it
will always return false.
7 fabio at naoimporta dot com ¶1 year ago~
It is interesting to be aware of the behavior when the treatment of
strings with characters using different encodings.
>
strlen($haystack))
trigger_error(sprintf("%s: length of argument 2 must be <= argument 1", __FUNCTION__), E_USER_WARNING);
$seeks = array();
while($seek = strrpos($haystack, $needle))
{
array_push($seeks, $seek);
$haystack = substr($haystack, 0, $seek);
}
return $seeks;
}
it will return an array of all occurrences a the substring in the string
Example :
$test = "this is a test for testing a test function... blah blah";
var_dump(strpos_r($test, "test"));
// output
array(3) {
[0]=>
int(29)
[1]=>
int(19)
[2]=>
int(10)
}
Paul-antoine
Malézieux.
up
down
13 rjeggens at ijskoud dot org ¶5 years ago
I lost an hour before I noticed that strpos only returns FALSE as a boolean, never TRUE.. This means that
strpos() !== false
is a different beast then:
strpos() === true
since the latter will never be true. After I found out, The warning in the documentation made a lot more sense.
up
down
15 akarmenia at gmail dot com ¶6 years ago
My version of strpos with needles as an array. Also allows for a string, or an array inside an array.
6 ohcc at 163 dot com ¶2 years ago~
Be careful when the $haystack or $needle parameter is an integer.
If you are not sure of its type, you should convert it into a string.
>
<
6 ilaymyhat-rem0ve at yahoo dot com ¶8 years ago~
This might be useful.
>
<
--------------------------------------------------------------------------------
*strrchr*
+---------+~
| strrchr |~
+---------+~
(PHP 4, PHP 5, PHP 7)
strrchr — Find the last occurrence of a character in a string
Description~
>
string strrchr ( string $haystack , mixed $needle )
<
This function returns the portion of haystack which starts at the last
occurrence of needle and goes until the end of haystack.
Parameters~
haystack
--------
The string to search in
needle
------
If needle contains more than one character, only the first is used.
This behavior is different from that of strstr().
If needle is not a string, it is converted to an integer and applied
as the ordinal value of a character.
Return Values~
This function returns the portion of string, or FALSE if needle is not found.
Changelog~
Version Description
4.3.0 This function is now binary safe.
Examples~
Example #1 strrchr() example
>
<
Notes
Note: This function is binary-safe.
See Also~
|strstr|() - Find the first occurrence of a string
|strrpos|() - Find the position of the last occurrence of a substring in a string
User Contributed Notes 10 notes
40 jphansen at uga dot edu ¶4 years ago~
To extract your portion of a string without the actual character you
searched for, you can use:
>
<
19 matthewkastor at live dot com ¶6 years ago~
>
* $example = 'http://example.com/path/file.php';
* $cwd_relative[] = cut_string_using_last('/', $example, 'left', true);
* $cwd_relative[] = cut_string_using_last('/', $example, 'left', false);
* $cwd_relative[] = cut_string_using_last('/', $example, 'right', true);
* $cwd_relative[] = cut_string_using_last('/', $example, 'right', false);
* foreach($cwd_relative as $string) {
* echo "$string ".PHP_EOL;
* }
*
*
* Outputs:
*
* http://example.com/path/
* http://example.com/path
* /file.php
* file.php
*
*
* @param string $character the character to search for.
* @param string $string the string to search through.
* @param string $side determines whether text to the left or the right of the character is returned.
* Options are: left, or right.
* @param bool $keep_character determines whether or not to keep the character.
* Options are: true, or false.
* @return string
*/
function cut_string_using_last($character, $string, $side, $keep_character=true) {
$offset = ($keep_character ? 1 : 0);
$whole_length = strlen($string);
$right_length = (strlen(strrchr($string, $character)) - 1);
$left_length = ($whole_length - $right_length - 1);
switch($side) {
case 'left':
$piece = substr($string, 0, ($left_length + $offset));
break;
case 'right':
$start = (0 - ($right_length + $offset));
$piece = substr($string, $start);
break;
default:
$piece = false;
break;
}
return($piece);
}
?>
<
9 readless at gmx dot net ¶10 years ago~
to: repley at freemail dot it
the code works very well, but as i was trying to cut script names (e.g.: $_SERVER["SCRIPT_NAME"] => /index.php, cut the string at "/" and return "index.php") it returned nothing (false). i've modified your code and now it works also if the needle is the first char.
- regards from germany
>
<
6 ¶11 years ago
$filename = 'strrchr_test.php';
print strrchr( $filename, '.' );
Result:
.php
$other_filename = 'strrchr_test.asp.php';
print strrchr( $other_filename, '.' );
Result:
.php
--------------------------------------------------------------------------------
*strrev*
+--------+~
| strrev |~
+--------+~
(PHP 4, PHP 5, PHP 7)
strrev — Reverse a string
Description~
>
string strrev ( string $string )
<
Returns string, reversed.
Parameters~
string
------
The string to be reversed.
Return Values~
Returns the reversed string.
Examples~
Example #1 Reversing a string with strrev()
>
<
User Contributed Notes 1 note
14 carmel.alex at gmail.com ¶11 years ago~
This function support utf-8 encoding
>
function utf8_strrev($str){
preg_match_all('/./us', $str, $ar);
return join('',array_reverse($ar[0]));
}
<
--------------------------------------------------------------------------------
*strripos*
+----------+~
| strripos |~
+----------+~
(PHP 5, PHP 7)
strripos — Find the position of the last occurrence of a case-insensitive substring in a string
Description~
>
int strripos ( string $haystack , string $needle [, int $offset = 0 ] )
<
Find the numeric position of the last occurrence of needle in the
haystack string.
Unlike the strrpos(), strripos() is case-insensitive.
Parameters~
haystack
--------
The string to search in.
needle
------
If needle is not a string, it is converted to an integer and applied
as the ordinal value of a character.
offset
------
If specified, search will start this number of characters counted from
the beginning of the string. If the value is negative, search will
instead start from that many characters from the end of the string,
searching backwards.
Return Values~
Returns the position where the needle exists relative to the
beginnning of the haystack string (independent of search direction or
offset). Also note that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
Warning
This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
Examples~
Example #1 A simple strripos() example
>
<
The above example will output:
Congratulations!
We found the last (aB) in (ababcd) at position (2)
See Also ¶
strpos() - Find the position of the first occurrence of a substring in a string
stripos() - Find the position of the first occurrence of a case-insensitive substring in a string
strrpos() - Find the position of the last occurrence of a substring in a string
strrchr() - Find the last occurrence of a character in a string
stristr() - Case-insensitive strstr
substr() - Return part of a string
--------------------------------------------------------------------------------
*strrpos*
+---------+~
| strrpos |~
+---------+~
(PHP 4, PHP 5, PHP 7)
strrpos — Find the position of the last occurrence of a substring in a string
Description~
>
int strrpos ( string $haystack , string $needle [, int $offset = 0 ] )
<
Find the numeric position of the last occurrence of needle in the
haystack string.
Parameters~
haystack
--------
The string to search in.
needle
------
If needle is not a string, it is converted to an integer and applied
as the ordinal value of a character.
offset
------
If specified, search will start this number of characters counted from
the beginning of the string. If the value is negative, search will
instead start from that many characters from the end of the string,
searching backwards.
Return Values~
Returns the position where the needle exists relative to the beginning
of the haystack string (independent of search direction or offset).
Also note that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
Warning
This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
Changelog~
Version Description
5.0.0 The needle may now be a string of more than one character.
Examples~
Example #1 Checking if a needle is in the haystack
It is easy to mistake the return values for "character found at
position 0" and "character not found". Here's how to detect the
difference:
>
<
Example #2 Searching with offsets
>
<
See Also~
|strpos|() - Find the position of the first occurrence of a substring in a string
|stripos|() - Find the position of the first occurrence of a case-insensitive substring in a string
|strripos|() - Find the position of the last occurrence of a case-insensitive substring in a string
|strrchr|() - Find the last occurrence of a character in a string
|substr|() - Return part of a string
User Contributed Notes 32 notes
32 brian at enchanter dot net ¶9 years ago~
The documentation for 'offset' is misleading.
It says, "offset may be specified to begin searching an arbitrary
number of characters into the string. Negative values will stop
searching at an arbitrary point prior to the end of the string."
This is confusing if you think of strrpos as starting at the end of the string and working backwards.
A better way to think of offset is:
- If offset is positive, then strrpos only operates on the part of the
string from offset to the end. This will usually have the same
results as not specifying an offset, unless the only occurences of
needle are before offset (in which case specifying the offset won't
find the needle).
- If offset is negative, then strrpos only operates on that many
characters at the end of the string. If the needle is farther away
from the end of the string, it won't be found.
If, for example, you want to find the last space in a string before
the 50th character, you'll need to do something like this:
strrpos($text, " ", -(strlen($text) - 50));
If instead you used strrpos($text, " ", 50), then you would find the
last space between the 50th character and the end of the string, which
may not have been what you were intending.
8 Daniel Brinca ¶9 years ago~
Here is a simple function to find the position of the next occurrence of needle in haystack, but searching backwards (lastIndexOf type function):
>
//search backwards for needle in haystack, and return its position
function rstrpos ($haystack, $needle, $offset){
$size = strlen ($haystack);
$pos = strpos (strrev($haystack), $needle, $size - $offset);
if ($pos === false)
return false;
return $size - $pos;
}
<
Note: supports full strings as needle
--------------------------------------------------------------------------------
*strspn*
+--------+~
| strspn |~
+--------+~
(PHP 4, PHP 5, PHP 7)
strspn — Finds the length of the initial segment of a string
consisting entirely of characters contained within a given mask.
Description~
>
int strspn ( string $subject , string $mask [, int $start [, int $length ]] )
<
Finds the length of the initial segment of subject that contains only
characters from mask.
If start and length are omitted, then all of subject will be examined.
If they are included, then the effect will be the same as calling
strspn(substr($subject, $start, $length), $mask) (see substr for more
information).
The line of code:
>
<
will assign 2 to $var, because the string "42" is the initial segment
of subject that consists only of characters contained within
"1234567890".
Parameters~
subject
-------
The string to examine.
mask
-----
The list of allowable characters.
start
-----
The position in subject to start searching.
If start is given and is non-negative, then strspn() will begin
examining subject at the start'th position. For instance, in the
string 'abcdef', the character at position 0 is 'a', the character at
position 2 is 'c', and so forth.
If start is given and is negative, then strspn() will begin examining
subject at the start'th position from the end of subject.
length
------
The length of the segment from subject to examine.
If length is given and is non-negative, then subject will be examined
for length characters after the starting position.
If length is given and is negative, then subject will be examined from
the starting position up to length characters from the end of subject.
Return Values~
Returns the length of the initial segment of subject which consists
entirely of characters in mask.
Note:
When a start parameter is set, the returned length is counted starting
from this position, not from the beginning of subject.
Examples~
Example #1 strspn() example
>
<
The above example will output:
int(0)
int(2)
int(1)
Notes
Note: This function is binary-safe.
See Also~
|strcspn|() - Find length of initial segment not matching mask
User Contributed Notes 6 notes
11 AT-HE (at_he.hotmail) ¶6 years ago~
you can use this function with strlen to check illegal characters,
string lenght must be the same than strspn (characters from my string
contained in another)
>
<
11 barry dot balkowski at gmail dot com ¶8 years ago~
It took me some time to understand the way this function works…
I’ve compiled my own explanation with my own words that is more
understandable for me personally than the official one or those that
can be found in different tutorials on the web.
Perhaps, it will save someone several minutes…
>
<
The way it works:
- searches for a segment of $haystack that consists entirely from
supplied through the second argument chars
- $haystack must start from one of the chars supplied through
$char_list, otherwise the function will find nothing
- as soon as the function encounters a char that was not mentioned
in $chars it understands that the segment is over and stops (it
doesn’t search for the second, third and so on segments)
- finally, it measures the segment’s length and return it (i.e.
length)
In other words it finds a span (only the first one) in the string that
consists entirely form chars supplied in $chars_list and returns its
length
6 B Crawford ¶9 years ago~
This function is significantly faster for checking illegal characters
than the equivalent preg_match() method.
--------------------------------------------------------------------------------
*strstr*
+--------+~
| strstr |~
+--------+~
(PHP 4, PHP 5, PHP 7)
strstr — Find the first occurrence of a string
Description~
>
string strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] )
<
Returns part of haystack string starting from and including the first
occurrence of needle to the end of haystack.
Note:
This function is case-sensitive. For case-insensitive searches, use
stristr().
Note:
If you only want to determine if a particular needle occurs within
haystack, use the faster and less memory intensive function strpos()
instead.
Parameters~
haystack
--------
The input string.
needle
------
If needle is not a string, it is converted to an integer and applied
as the ordinal value of a character.
before_needle
-------------
If TRUE, strstr() returns the part of the haystack before the first
occurrence of the needle (excluding the needle).
Return Values~
Returns the portion of string, or FALSE if needle is not found.
Changelog~
Version Description
5.3.0 Added the optional parameter before_needle.
4.3.0 strstr() was made binary safe.
Examples~
Example #1 strstr() example
>
<
See Also~
|stristr|() - Case-insensitive strstr
|strrchr|() - Find the last occurrence of a character in a string
|strpos|() - Find the position of the first occurrence of a substring in a string
|strpbrk|() - Search a string for any of a set of characters
|preg_match|() - Perform a regular expression match
User Contributed Notes 8 notes
21 gruessle at gmail dot com ¶5 years ago~
Been using this for years:
>
<
You could change it to:
rstrstr ( string $haystack , mixed $needle [, int $start] )
>
<
15 laszlo dot heredy at gmail dot com ¶3 years ago~
strstr() is not a way to avoid type-checking with strpos().
If $needle is the last character in $haystack, and testing $needle as
a boolean by itself would evaluate to false, then testing strstr() as
a boolean will evaluate to false (because, if successful, strstr()
returns the first occurrence of $needle along with the rest of
$haystack).
>
<
Also, strstr() is far more memory-intensive than strpos(), especially
with longer strings as your $haystack, so if you are not interested in
the substring that strstr() returns, you shouldn't be using it anyway.
There is no PHP function just to check only _if_ $needle occurs in
$haystack; strpos() tells you if it _doesn't_ by returning false, but,
if it does occur, it tells you _where_ it occurs as an integer, which
is 0 (zero) if $needle is the first part of $haystack, which is why
testing if (strpos($needle, $haystack)===false) is the only way to
know for sure if $needle is not part of $haystack.
My advice is to start loving type checking immediately, and to
familiarize yourself with the return value of the functions you are
using.
Cheers.
9 brett dot jr dot alton at gmail dot com ¶9 years ago~
For the needle_before (first occurance) parameter when using PHP 5.x
or less, try:
>
<
--------------------------------------------------------------------------------
*strtok*
+--------+~
| strtok |~
+--------+~
(PHP 4, PHP 5, PHP 7)
strtok — Tokenize string
Description~
>
string strtok ( string $str , string $token )
string strtok ( string $token )
<
strtok() splits a string (str) into smaller strings (tokens), with
each token being delimited by any character from token. That is, if
you have a string like "This is an example string" you could tokenize
this string into its individual words by using the space character as
the token.
Note that only the first call to strtok uses the string argument.
Every subsequent call to strtok only needs the token to use, as it
keeps track of where it is in the current string. To start over, or to
tokenize a new string you simply call strtok with the string argument
again to initialize it. Note that you may put multiple tokens in the
token parameter. The string will be tokenized when any one of the
characters in the argument is found.
Parameters~
str
-----
The string being split up into smaller strings (tokens).
token
-----
The delimiter used when splitting up str.
Return Values~
A string token.
Examples~
Example #1 strtok() example
>
";
$tok = strtok(" \n\t");
}
?>
<
Example #2 strtok() behavior on empty part found
>
<
The above example will output:
string(9) "something"
bool(false)
Notes
Warning
This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
See Also~
|split|() - Split string into array by regular expression
|explode|() - Split a string by string
User Contributed Notes 17 notes
16 manicdepressive at mindless dot com ¶12 years ago~
>
<
29 eep2004 at ukr dot net ¶3 years ago~
>
<
Result:
Hello to all
8 elarlang at gmail dot com ¶6 years ago~
If you have memory-usage critical solution, you should keep in mind,
that strtok function holds input string parameter (or reference to
it?) in memory after usage.
>
<
Test-cases with handling ~10MB plain-text file:
Case #1 - unset $str variable
>
<
Case #1 result: memory is still used
Case #2 - call strtok again
>
<
Case #2 result: memory is still used
Case #3 - call strtok again AND unset $str variable
>
<
Case #3 result: memory is free
So, better solution for tokenize function:
>
<
7 eep2004 at ukr dot net ¶2 years ago~
Remove GET variables from the URL
>
<
Result:
http://example.com/index.php
--------------------------------------------------------------------------------
*strtolower*
+------------+~
| strtolower |~
+------------+~
(PHP 4, PHP 5, PHP 7)
strtolower — Make a string lowercase
Description~
>
string strtolower ( string $string )
<
Returns string with all alphabetic characters converted to lowercase.
Note that 'alphabetic' is determined by the current locale. This means
that e.g. in the default "C" locale, characters such as umlaut-A (Ä)
will not be converted.
Parameters~
string
------
The input string.
Return Values~
Returns the lowercased string.
Examples~
Example #1 strtolower() example
>
<
Notes
Note: This function is binary-safe.
See Also~
|strtoupper|() - Make a string uppercase
|ucfirst|() - Make a string's first character uppercase
|ucwords|() - Uppercase the first character of each word in a string
|mb_strtolower|() - Make a string lowercase
User Contributed Notes 16 notes
66 marcin at maydesign dot pl ¶6 years ago~
strtolower(); doesn't work for polish chars
>
<
will return: mAka;
the best solution - use mb_strtolower()
>
<
will return: maka
31 coder at bulgaria dot bg ¶7 years ago~
for cyrillic and UTF 8 use mb_convert_case
exampel
>
<
7 helvete at bahno dot net ¶2 years ago~
It is worth noting that
>
<
returns:
string(0) ""
7 rodrigoATsistemasparainternetDOTcomDOTbr ¶8 years ago~
>
$value) {
$result = ereg_replace(addslashes($value),$key,$result);
}
return(strtolower($result));
}
echo fullLower("Ã É Ò Õ ÚÙÛ");
//results ã é ò õ úùû
//adapted from fullUpper on strtoupper manual
?>
<
6 dbers26 at gmail dot com ¶8 years ago~
the function arraytolower will create duplicate entries since keys
are case sensitive.
>
'asgAFasDAAd', 'TEST2' => 'ASddhshsDGb', 'TeSt3 '=> 'asdasda@asdadadASDASDgh');
$array = arraytolower($array);
?>
<
/*
Array
(
[test1] => asgafasdaad
[TEST2] => ASddhshsDGb
[TeSt3] => asdasda@asdadadASDASDgh
[test2] => asddhshsdgb
[test3] => asdasda@asdadadasdasdgh
)
*/
I prefer this method
>
$value) {
if(is_array($value))
$array2[strtolower($key)] = arraytolower($value, $include_leys);
else
$array2[strtolower($key)] = strtolower($value);
}
$array = $array2;
}
else {
foreach($array as $key => $value) {
if(is_array($value))
$array[$key] = arraytolower($value, $include_leys);
else
$array[$key] = strtolower($value);
}
}
return $array;
}
?>
<
which when used like this
>
'asgAFasDAAd', 'TEST2' => 'ASddhshsDGb', 'TeSt3 '=> 'asdasda@asdadadASDASDgh');
$array1 = arraytolower($array);
$array2 = arraytolower($array,true);
print_r($array1);
print_r($array2);
?>
<
will give output of
Array
(
[test1] => asgafasdaad
[TEST2] => asddhshsdgb
[TeSt3] => asdasda@asdadadasdasdgh
)
Array
(
[test1] => asgafasdaad
[test2] => asddhshsdgb
[test3] => asdasda@asdadadasdasdgh
)
--------------------------------------------------------------------------------
*strtoupper*
+------------+~
| strtoupper |~
+------------+~
(PHP 4, PHP 5, PHP 7)
strtoupper — Make a string uppercase
Description~
>
string strtoupper ( string $string )
<
Returns string with all alphabetic characters converted to uppercase.
Note that 'alphabetic' is determined by the current locale. For
instance, in the default "C" locale characters such as umlaut-a (ä)
will not be converted.
Parameters~
string
------
The input string.
Return Values~
Returns the uppercased string.
Examples~
Example #1 strtoupper() example
>
<
Notes
Note: This function is binary-safe.
See Also~
|strtolower|() - Make a string lowercase
|ucfirst|() - Make a string's first character uppercase
|ucwords|() - Uppercase the first character of each word in a string
|mb_strtoupper|() - Make a string uppercase
User Contributed Notes 14 notes
32 andre at koethur dot de ¶3 years ago~
One might think that setting the correct locale would do the trick
with for example german umlauts, but this is not the case. You have to
use mb_strtoupper() instead:
>
<
6 Anonymous ¶11 years ago~
// 2005/5/30 Justin
// Chinese_Traditional toupper
function CT_to_upper($string)
{
$isChineseStart = false;
$new_string = "";
$i = 0;
while($i < strlen($string))
{
if (ord(substr($string,$i,1)) <128)
{
if( $isChineseStart == false )
$new_string .= strtoupper(mb_substr($string,$i,1));
else
$new_string .= substr($string,$i,1);
}
else
{
if( $isChineseStart == false )
$isChineseStart = true;
else
$isChineseStart = false;
$new_string .= substr($string,$i,1);
}
$i++;
}
return $new_string;
}
//
6 mec at stadeleck dot org ¶14 years ago~
something I myself first not thought about: if there are any html
entities (named entities) in your string, strtoupper will turn all
letters within this entities to upper case, too. So if you want to
manipulate a string with strtoupper it should contain only unicode
entities (if ever).
--------------------------------------------------------------------------------
*strtr*
+-------+~
| strtr |~
+-------+~
(PHP 4, PHP 5, PHP 7)
strtr — Translate characters or replace substrings
Description~
>
string strtr ( string $str , string $from , string $to )
string strtr ( string $str , array $replace_pairs )
<
If given three arguments, this function returns a copy of str where
all occurrences of each (single-byte) character in from have been
translated to the corresponding character in to, i.e., every
occurrence of $from[$n] has been replaced with $to[$n], where $n is a
valid offset in both arguments.
If from and to have different lengths, the extra characters in the
longer of the two are ignored. The length of str will be the same as
the return value's.
If given two arguments, the second should be an array in the form
array('from' => 'to', ...). The return value is a string where all the
occurrences of the array keys have been replaced by the corresponding
values. The longest keys will be tried first. Once a substring has
been replaced, its new value will not be searched again.
In this case, the keys and the values may have any length, provided
that there is no empty key; additionally, the length of the return
value may differ from that of str. However, this function will be the
most efficient when all the keys have the same size.
Parameters~
str
-----
The string being translated.
from
-----
The string being translated to to.
to
-----
The string replacing from.
replace_pairs
-------------
The replace_pairs parameter may be used instead of to and from, in
which case it's an array in the form array('from' => 'to', ...).
Return Values~
Returns the translated string.
If replace_pairs contains a key which is an empty string (""), FALSE
will be returned. If the str is not a scalar then it is not typecasted
into a string, instead a warning is raised and NULL is returned.
Examples~
Example #1 strtr() example
>
<
The next example shows the behavior of strtr() when called with only
two arguments. Note the preference of the replacements ("h" is not
picked because there are longer matches) and how replaced text was not
searched again.
Example #2 strtr() example with two arguments
>
"-", "hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
?>
<
The above example will output:
hello all, I said hi
The two modes of behavior are substantially different. With three
arguments, strtr() will replace bytes; with two, it may replace longer
substrings.
Example #3 strtr() behavior comparison
>
"01");
echo strtr("baab", $trans);
?>
<
The above example will output:
1001
ba01
See Also~
|str_replace|() - Replace all occurrences of the search string with the replacement string
|preg_replace|() - Perform a regular expression search and replace
User Contributed Notes 40 notes
24 evan dot king at NOSPAM dot example dot com ¶1 year ago~
Here's an important real-world example use-case for strtr where
str_replace will not work or will introduce obscure bugs:
>
'Dave',
'Dave' => ':name2 or :password', // a wrench in the otherwise sensible input
':name2' => 'Steve',
':pass' => '7hf2348', // sensitive data that maybe shouldn't be here
];
echo strtr($strTemplate, $strParams);
// "My name is Dave, not Steve."
echo str_replace(array_keys($strParams), array_values($strParams), $strTemplate);
// "My name is Steve or 7hf2348word, not Steve or 7hf2348word2."
?>
<
Any time you're trying to template out a string and don't necessarily
know what the replacement keys/values will be (or fully understand the
implications of and control their content and order), str_replace will
introduce the potential to incorrectly match your keys because it does
not expand the longest keys first.
Further, str_replace will replace in previous replacements,
introducing potential for unintended nested expansions. Doing so can
put the wrong data into the "sub-template" or even give users a chance
to provide input that exposes data (if they get to define some of the
replacement strings).
Don't support recursive expansion unless you need it and know it will
be safe. When you do support it, do so explicitly by repeating strtr
calls until no more expansions are occurring or a sane iteration limit
is reached, so that the results never implicitly depend on order of
your replacement keys. Also make certain that any user input will
expanded in an isolated step after any sensitive data is already
expanded into the output and no longer available as input.
Note: using some character(s) around your keys to designate them also
reduces the possibility of unintended mangling of output, whether
maliciously triggered or otherwise. Thus the use of a colon prefix in
these examples, which you can easily enforce when accepting
replacement input to your templating/translation system.
21 Hayley Watson ¶4 years ago~
Since strtr (like PHP's other string functions) treats strings as a
sequence of bytes, and since UTF-8 and other multibyte encodings use -
by definition - more than one byte for at least some characters, the
three-string form is likely to have problems. Use the associative
array form to specify the mapping.
>
'a')); // Works much better
?>
<
7 dcz at phpbb-seo dot com ¶3 years ago~
strstr will issue a notice when $replace_pairs contains an array, even
unused, with php 5.5.0.
It was not the case with version at least up to 5.3.2, but I'm not
sure the notice was added with exactly 5.5.0.
>
'everybody',
'unused' => array('somtehing', 'something else'),
'hello' => 'hey',
);
// php 5.5.0 Notice: Array to string conversion in test.php on line 8
echo strtr($str, $replace_pairs); // hi everybody, I said hey
?>
<
since the result is still correct, @strstr seems a working solution.
--------------------------------------------------------------------------------
*substr_compare*
+----------------+~
| substr_compare |~
+----------------+~
(PHP 5, PHP 7)
substr_compare — Binary safe comparison of two strings from an offset,
up to length characters
Description~
>
int substr_compare ( string $main_str , string $str , int $offset [, int $length [, bool $case_insensitivity = false ]] )
<
substr_compare() compares main_str from position offset with str up to length characters.
Parameters~
main_str
--------
The main string being compared.
str
-----
The secondary string being compared.
offset
------
The start position for the comparison. If negative, it starts counting
from the end of the string.
length
------
The length of the comparison. The default value is the largest of the
length of the str compared to the length of main_str less the offset.
case_insensitivity
------------------
If case_insensitivity is TRUE, comparison is case insensitive.
Return Values~
Returns < 0 if main_str from position offset is less than str, > 0 if
it is greater than str, and 0 if they are equal. If offset is equal to
or greater than the length of main_str, or the length is set and is
less than 1 (prior to PHP 5.6), substr_compare() prints a warning and
returns FALSE.
Changelog~
Version Description
5.6.0 length may now be 0.
5.1.0 Added the possibility to use a negative offset.
Examples~
Example #1 A substr_compare() example
>
<
See Also~
|strncmp|() - Binary safe string comparison of the first n characters
User Contributed Notes 4 notes
16 jimmetry at gmail dot com ¶4 years ago~
When you came to this page, you may have been looking for something a
little simpler: A function that can check if a small string exists
within a larger string starting at a particular index. Using
substr_compare() for this can leave your code messy, because you need
to check that your string is long enough (to avoid the warning),
manually specify the length of the short string, and like many of the
string functions, perform an integer comparison to answer a true/false
question.
I put together a simple function to return true if $str exists within
$mainStr. If $loc is specified, the $str must begin at that index. If
not, the entire $mainStr will be searched.
>
strlen($mainStr)) return false;
return (strcmp(substr($mainStr, $loc, strlen($str)), $str) == 0);
}
?>
7 Skyborne ¶4 years ago~
Take note of the `length` parameter: "The default value is the largest
of the length of the str compared to the length of main_str less the
offset."
This is *not* the length of str as you might (I always) expect, so if
you leave it out, you'll get unexpected results. Example:
>
<
--------------------------------------------------------------------------------
*substr_count*
+--------------+~
| substr_count |~
+--------------+~
(PHP 4, PHP 5, PHP 7)
substr_count — Count the number of substring occurrences
Description~
>
int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )
<
substr_count() returns the number of times the needle substring occurs
in the haystack string. Please note that needle is case sensitive.
Note:
This function doesn't count overlapped substrings. See the example below!
Parameters~
haystack
--------
The string to search in
needle
------
The substring to search for
offset
------
The offset where to start counting. If the offset is negative,
counting starts from the end of the string.
length
------
The maximum length after the specified offset to search for the
substring. It outputs a warning if the offset plus the length is
greater than the haystack length. A negative length counts from the
end of haystack.
Return Values~
This function returns an integer.
Changelog~
Version Description
7.1.0 Support for negative offsets and lengths has been added.
5.1.0 Added the offset and the length parameters
Examples~
Example #1 A substr_count() example
>
14
echo substr_count($text, 'is', 5, 10);
// prints only 1, because it doesn't count overlapped substrings
$text2 = 'gcdgcdgcd';
echo substr_count($text2, 'gcdgcd');
?>
<
See Also~
|count_chars|() - Return information about characters used in a string
|strpos|() - Find the position of the first occurrence of a substring in a string
|substr|() - Return part of a string
|strstr|() - Find the first occurrence of a string
User Contributed Notes 10 notes
8 jrhodes at roket-enterprises dot com ¶7 years ago~
It was suggested to use
substr_count ( implode( $haystackArray ), $needle );
instead of the function described previously, however this has one
flaw. For example this array:
array (
0 => "mystringth",
1 => "atislong"
);
If you are counting "that", the implode version will return 1, but the function previously described will return 0.
7 flobi at flobi dot com ¶10 years ago~
Making this case insensitive is easy for anyone who needs this.
Simply convert the haystack and the needle to the same case (upper or
lower).
substr_count(strtoupper($haystack), strtoupper($needle))
--------------------------------------------------------------------------------
*substr_replace*
+----------------+~
| substr_replace |~
+----------------+~
(PHP 4, PHP 5, PHP 7)
substr_replace — Replace text within a portion of a string
Description~
>
mixed substr_replace ( mixed $string , mixed $replacement , mixed $start [, mixed $length ] )
<
substr_replace() replaces a copy of string delimited by the start and
(optionally) length parameters with the string given in replacement.
Parameters~
string
------
The input string.
An array of strings can be provided, in which case the replacements
will occur on each string in turn. In this case, the replacement,
start and length parameters may be provided either as scalar values to
be applied to each input string in turn, or as arrays, in which case
the corresponding array element will be used for each input string.
replacement
-----------
The replacement string.
start
-----
If start is non-negative, the replacing will begin at the start'th
offset into string.
If start is negative, the replacing will begin at the start'th
character from the end of string.
length
------
If given and is positive, it represents the length of the portion of
string which is to be replaced. If it is negative, it represents the
number of characters from the end of string at which to stop
replacing. If it is not given, then it will default to strlen( string
); i.e. end the replacing at the end of string. Of course, if length
is zero then this function will have the effect of inserting
replacement into string at the given start offset.
Return Values~
The result string is returned. If string is an array then array is
returned.
Examples~
Example #1 Simple substr_replace() examples
>
\n";
/* These two examples replace all of $var with 'bob'. */
echo substr_replace($var, 'bob', 0) . " \n";
echo substr_replace($var, 'bob', 0, strlen($var)) . " \n";
/* Insert 'bob' right at the beginning of $var. */
echo substr_replace($var, 'bob', 0, 0) . " \n";
/* These next two replace 'MNRPQR' in $var with 'bob'. */
echo substr_replace($var, 'bob', 10, -1) . " \n";
echo substr_replace($var, 'bob', -7, -1) . " \n";
/* Delete 'MNRPQR' from $var. */
echo substr_replace($var, '', 10, -1) . " \n";
?>
<
Example #2 Using substr_replace() to replace multiple strings at once
>
<
The above example will output:
A: YYY; B: YYY; C: YYY
A: AAA; B: BBB; C: CCC
A: AAAXX; B: BBBX; C: CCC
Notes
Note: This function is binary-safe.
See Also~
|str_replace|() - Replace all occurrences of the search string with the replacement string
|substr|() - Return part of a string
User Contributed Notes 30 notes
16 elloromtz at gmail dot com ¶6 years ago~
It's worth noting that when start and length are both negative -and-
the length is less than or equal to start, the length will have the
effect of being set as 0.
>
<
Same as:
>
<
Same as:
>
<
Another note, if length is negative and start offsets the same
position as length, length (yet again) will have the effect as being
set as 0. (Of course, as mentioned in the manual, when length is
negative it actually represents the position before it)
>
<
Same as:
>
<
Same as:
>
<
7 juichenieder-phnet at yahoo dot co dot uk ¶8 years ago~
I've just taken a look at the post by ntoniazzi and I have a very
small correction to make.
In the second if statement, it should be a triple equals, so:
It requires the triple equals, for the case of pure insertion, where
$length = 0, the double equals, will catch this, causing the string to
be cut short. I hope this helps someone.
7 ivijan dot stefan at gmail dot com ¶3 years ago~
I have a little function that works like substr_replace () what I use for some purpose. Maybe someone needs it.
>
$d[0]) $position=$d[0];
for($i=$d[0]; $i >= $position; $i--) $string[$i+$d[1]]=$string[$i];
for($i=0; $i<$d[1]; $i++) $string[$position+$i]=$put[$i];
return $string;
}
// Explanation
$string='My dog dont love postman'; // string
$put="'"; // put ' on position
$position=10; // number of characters (position)
print_r( putinplace($string, $put, $position) );
?>
<
RESULT: My dog don't love postman
This is a small powerful function that performs its job flawlessly.
--------------------------------------------------------------------------------
*substr*
+--------+~
| substr |~
+--------+~
(PHP 4, PHP 5, PHP 7)
substr — Return part of a string
Description~
>
string substr ( string $string , int $start [, int $length ] )
<
Returns the portion of string specified by the start and length
parameters.
Parameters~
string
------
The input string. Must be one character or longer.
start
-----
If start is non-negative, the returned string will start at the
start'th position in string, counting from zero. For instance, in the
string 'abcdef', the character at position 0 is 'a', the character at
position 2 is 'c', and so forth.
If start is negative, the returned string will start at the start'th
character from the end of string.
If string is less than start characters long, FALSE will be returned.
Example #1 Using a negative start
>
<
length
------
If length is given and is positive, the string returned will contain
at most length characters beginning from start (depending on the
length of string).
If length is given and is negative, then that many characters will be
omitted from the end of string (after the start position has been
calculated when a start is negative). If start denotes the position of
this truncation or beyond, FALSE will be returned.
If length is given and is 0, FALSE or NULL, an empty string will be
returned.
If length is omitted, the substring starting from start until the end
of the string will be returned.
Example #2 Using a negative length
>
<
Return Values~
Returns the extracted part of string; or FALSE on failure, or an empty
string.
Changelog~
Version Description
7.0.0 If string is equal to start characters long, an empty string
will be returned. Prior to this version, FALSE was returned in this
case.
5.2.2 - 5.2.6 If the start parameter indicates the position of a
negative truncation or beyond, false is returned. Other versions get
the string from start.
Examples~
Example #3 Basic substr() usage
>
<
Example #4 substr() casting behaviour
>
<
Output of the above example in PHP 7:
1) 'pe'
2) '54'
3) 'gr'
4) '1'
5) ''
6) ''
7) '1200'
Output of the above example in PHP 5:
1) 'pe'
2) '54'
3) 'gr'
4) '1'
5) false
6) false
7) '1200'
Errors/Exceptions ¶
Returns FALSE on error.
>
<
See Also~
|strrchr|() - Find the last occurrence of a character in a string
|substr_replace|() - Replace text within a portion of a string
|preg_match|() - Perform a regular expression match
|trim|() - Strip whitespace (or other characters) from the beginning and end of a string
|mb_substr|() - Get part of string
|wordwrap|() - Wraps a string to a given number of characters
User Contributed Notes 47 notes
79 Andreas Bur (andreas dot buro at gmail dot com) ¶7 years ago~
For getting a substring of UTF-8 characters, I highly recommend mb_substr
>
<
59 biohazard dot ge at gmail dot com ¶3 years ago~
may be by following functions will be easier to extract the needed sub
parts from a string:
>
<
here comes the source:
>
<
11 fanfatal at fanfatal dot pl ¶11 years ago~
Hmm ... this is a script I wrote, whitch is very similar to substr,
but it isn't takes html and bbcode for counting and it takes portion
of string and show avoided (html & bbcode) tags too ;]
Specially usefull for show part of serach result included html and
bbcode tags
>
]*?>|<\/\w+>)/i';
$clean = preg_replace($pattern, chr(1), $string);
if(!$length)
$str = substr($clean, $start);
else {
$str = substr($clean, $start, $length);
$str = substr($clean, $start, $length + substr_count($str, chr(1)));
}
$pattern = str_replace(chr(1),'(.*?)',preg_quote($str));
if(preg_match('/'.$pattern.'/is', $string, $matched))
return $matched[0];
return $string;
}
?>
<
Using this is similar to simple substr.
Greatings ;]
...
--------------------------------------------------------------------------------
*trim*
+------+~
| trim |~
+------+~
(PHP 4, PHP 5, PHP 7)
trim — Strip whitespace (or other characters) from the beginning and
end of a string
Description~
>
string trim ( string $str [, string $character_mask = " \t\n\r\0\x0B" ] )
<
This function returns a string with whitespace stripped from the
beginning and end of str. Without the second parameter, trim() will
strip these characters:
" " (ASCII 32 (0x20)), an ordinary space.
"\t" (ASCII 9 (0x09)), a tab.
"\n" (ASCII 10 (0x0A)), a new line (line feed).
"\r" (ASCII 13 (0x0D)), a carriage return.
"\0" (ASCII 0 (0x00)), the NUL-byte.
"\x0B" (ASCII 11 (0x0B)), a vertical tab.
Parameters~
str
-----
The string that will be trimmed.
character_mask
--------------
Optionally, the stripped characters can also be specified using the
character_mask parameter. Simply list all characters that you want to
be stripped. With .. you can specify a range of characters.
Return Values~
The trimmed string.
Examples~
Example #1 Usage example of trim()
>
<
The above example will output:
string(32) " These are a few words :) ... "
string(16) " Example string
"
string(11) "Hello World"
string(28) "These are a few words :) ..."
string(24) "These are a few words :)"
string(5) "o Wor"
string(9) "ello Worl"
string(14) "Example string"
Example #2 Trimming array values with trim()
>
<
The above example will output:
array(3) {
[0]=>
string(5) "apple"
[1]=>
string(7) "banana "
[2]=>
string(11) " cranberry "
}
array(3) {
[0]=>
string(5) "apple"
[1]=>
string(6) "banana"
[2]=>
string(9) "cranberry"
}
Notes~
Note: Possible gotcha: removing middle characters
Because trim() trims characters from the beginning and end of a
string, it may be confusing when characters are (or are not) removed
from the middle. trim('abc', 'bad') removes both 'a' and 'b' because
it trims 'a' thus moving 'b' to the beginning to also be trimmed. So,
this is why it "works" whereas trim('abc', 'b') seemingly does not.
See Also~
|ltrim|() - Strip whitespace (or other characters) from the beginning of a string
|rtrim|() - Strip whitespace (or other characters) from the end of a string
|str_replace|() - Replace all occurrences of the search string with the replacement string
User Contributed Notes 7 notes
39 Piopier ¶10 years ago~
It may be useful to know that trim() returns an empty string when the
argument is an unset/null variable.
36 ludko2 at gmail dot com ¶6 years ago~
Non-breaking spaces can be troublesome with trim:
>
>
// UTF encodes it as chr(0xC2).chr(0xA0)
$converted = trim($converted,chr(0xC2).chr(0xA0)); // should work
// PS: Thanks to John for saving my sanity!
?>
<
22 jubi at irc dot pl ¶12 years ago~
To remove multiple occurences of whitespace characters in a string an
convert them all into single spaces, use this:
>
$text = preg_replace('/\s+/', ' ', $text);
?>
<
------------
JUBI
http://www.jubi.buum.pl
--------------------------------------------------------------------------------
*ucfirst*
+---------+~
| ucfirst |~
+---------+~
(PHP 4, PHP 5, PHP 7)
ucfirst — Make a string's first character uppercase
Description~
>
string ucfirst ( string $str )
<
Returns a string with the first character of str capitalized, if that
character is alphabetic.
Note that 'alphabetic' is determined by the current locale. For
instance, in the default "C" locale characters such as umlaut-a (ä)
will not be converted.
Parameters~
str
-----
The input string.
Return Values~
Returns the resulting string.
Examples~
Example #1 ucfirst() example
>
<
See Also~
|lcfirst|() - Make a string's first character lowercase
|strtolower|() - Make a string lowercase
|strtoupper|() - Make a string uppercase
|ucwords|() - Uppercase the first character of each word in a string
User Contributed Notes 32 notes
48 plemieux ¶11 years ago~
Simple multi-bytes ucfirst():
>
<
18 mattalexxpub at gmail dot com ¶8 years ago~
This is what I use for converting strings to sentence case:
>
$sentence) {
$new_string .= ($key & 1) == 0?
ucfirst(strtolower(trim($sentence))) :
$sentence.' ';
}
return trim($new_string);
}
print sentence_case('HMM. WOW! WHAT?');
// Outputs: "Hmm. Wow! What?"
?>
<
12 svetoslavm at gmail dot com ¶8 years ago
For some reason this worked for me.
Mac OS 10.5.1
PHP 5.2.6
>
<
Svetoslav Marinov
http://slavi.biz
10 prokur.net - there is my email ¶8 years ago~
I believe that mb_ucfirst will be soon added in PHP, but for now this could be useful
>
<
it also check is mb support enabled or not
--------------------------------------------------------------------------------
*ucwords*
+---------+~
| ucwords |~
+---------+~
(PHP 4, PHP 5, PHP 7)
ucwords — Uppercase the first character of each word in a string
Description~
>
string ucwords ( string $str [, string $delimiters = " \t\r\n\f\v" ] )
<
Returns a string with the first character of each word in str
capitalized, if that character is alphabetic.
The definition of a word is any string of characters that is
immediately after any character listed in the delimiters parameter (By
default these are: space, form-feed, newline, carriage return,
horizontal tab, and vertical tab).
Parameters~
str
-----
The input string.
delimiters
----------
The optional delimiters contains the word separator characters.
Return Values~
Returns the modified string.
Changelog~
Version Description
5.4.32, 5.5.16 Added the delimiters parameter.
Examples~
Example #1 ucwords() example
>
<
Example #2 ucwords() example with custom delimiter
>
<
Notes
Note: This function is binary-safe.
See Also~
|strtoupper|() - Make a string uppercase
|strtolower|() - Make a string lowercase
|ucfirst|() - Make a string's first character uppercase
|mb_convert_case|() - Perform case folding on a string
User Contributed Notes 54 notes
49 jmarois at ca dot ibm dot com ¶7 years ago~
My quick and dirty ucname (Upper Case Name) function.
>
<
You can add more delimiters in the for-each loop array if you want to
handle more characters.
24 antoniomax at antoniomax dot com ¶3 years ago~
Para formatar nomes em pt-br:
>
$delimiter) {
$words = explode($delimiter, $string);
$newwords = array();
foreach ($words as $wordnr => $word) {
if (in_array(mb_strtoupper($word, "UTF-8"), $exceptions)) {
// check exceptions list for any words that should be in upper case
$word = mb_strtoupper($word, "UTF-8");
} elseif (in_array(mb_strtolower($word, "UTF-8"), $exceptions)) {
// check exceptions list for any words that should be in upper case
$word = mb_strtolower($word, "UTF-8");
} elseif (!in_array($word, $exceptions)) {
// convert to uppercase (non-utf8 only)
$word = ucfirst($word);
}
array_push($newwords, $word);
}
$string = join($delimiter, $newwords);
}//foreach
return $string;
}
?>
<
Usage:
>
<
12 robert at broofa dot com ¶7 years ago~
Some recipes for switching between underscore and camelcase naming:
>
"ThisMethodName"
preg_replace('/(?:^|_)(.?)/e',"strtoupper('$1')",$string);
// underscored to lower-camelcase
// e.g. "this_method_name" -> "thisMethodName"
preg_replace('/_(.?)/e',"strtoupper('$1')",$string);
// camelcase (lower or upper) to underscored
// e.g. "thisMethodName" -> "this_method_name"
// e.g. "ThisMethodName" -> "this_method_name"
strtolower(preg_replace('/([^A-Z])([A-Z])/', "$1_$2", $string));
?>
<
Of course these aren't 100% symmetric. For example...
* this_is_a_string -> ThisIsAString -> this_is_astring
* GetURLForString -> get_urlfor_string -> GetUrlforString
--------------------------------------------------------------------------------
*vfprintf*
+----------+~
| vfprintf |~
+----------+~
(PHP 5, PHP 7)
vfprintf — Write a formatted string to a stream
Description~
>
int vfprintf ( resource $handle , string $format , array $args )
<
Write a string produced according to format to the stream resource
specified by handle.
Operates as fprintf() but accepts an array of arguments, rather than a
variable number of arguments.
Parameters~
handle
------
format
See sprintf() for a description of format.
args
-----
Return Values~
Returns the length of the outputted string.
Examples~
Example #1 vfprintf(): zero-padded integers
>
<
See Also~
|printf|() - Output a formatted string
|sprintf|() - Return a formatted string
|sscanf|() - Parses input from a string according to a format
|fscanf|() - Parses input from a file according to a format
|vsprintf|() - Return a formatted string
|number_format|() - Format a number with grouped thousands
--------------------------------------------------------------------------------
*vprintf*
+---------+~
| vprintf |~
+---------+~
(PHP 4 >= 4.1.0, PHP 5, PHP 7)
vprintf — Output a formatted string
Description~
>
int vprintf ( string $format , array $args )
<
Display array values as a formatted string according to format (which
is described in the documentation for sprintf()).
Operates as printf() but accepts an array of arguments, rather than a
variable number of arguments.
Parameters~
format
------
See sprintf() for a description of format.
args
-----
Return Values~
Returns the length of the outputted string.
Examples~
Example #1 vprintf(): zero-padded integers
>
<
See Also~
|printf|() - Output a formatted string
|sprintf|() - Return a formatted string
|vsprintf|() - Return a formatted string
--------------------------------------------------------------------------------
*vsprintf*
+----------+~
| vsprintf |~
+----------+~
(PHP 4 >= 4.1.0, PHP 5, PHP 7)
vsprintf — Return a formatted string
Description~
>
string vsprintf ( string $format , array $args )
<
Operates as sprintf() but accepts an array of arguments, rather than a
variable number of arguments.
Parameters~
format
------
See sprintf() for a description of format.
args
-----
Return Values~
Return array values as a formatted string according to format (which
is described in the documentation for sprintf()).
Examples~
Example #1 vsprintf(): zero-padded integers
>
<
See Also~
|sprintf|() - Return a formatted string
|vprintf|() - Output a formatted string
User Contributed Notes 13 notes
12 Josef Kufner ¶4 years ago~
>
1, 'y' => 2))
* Result: 'y = 2, x = 1.0'
*
* $args also can be object, then it's properties are retrieved
* using get_object_vars().
*
* '%s' without argument name works fine too. Everything vsprintf() can do
* is supported.
*
* @author Josef Kufner
*/
function vksprintf($str, $args)
{
if (is_object($args)) {
$args = get_object_vars($args);
}
$map = array_flip(array_keys($args));
$new_str = preg_replace_callback('/(^|[^%])%([a-zA-Z0-9_-]+)\$/',
function($m) use ($map) { return $m[1].'%'.($map[$m[2]] + 1).'$'; },
$str);
return vsprintf($new_str, $args);
}
?>
<
--------------------------------------------------------------------------------
*wordwrap*
+----------+~
| wordwrap |~
+----------+~
(PHP 4 >= 4.0.2, PHP 5, PHP 7)
wordwrap — Wraps a string to a given number of characters
Description~
>
string wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = false ]]] )
<
Wraps a string to a given number of characters using a string break
character.
Parameters~
str
-----
The input string.
width
-----
The number of characters at which the string will be wrapped.
break
-----
The line is broken using the optional break parameter.
cut
-----
If the cut is set to TRUE, the string is always wrapped at or before
the specified width. So if you have a word that is larger than the
given width, it is broken apart. (See second example). When FALSE the
function does not split the word even if the width is smaller than the
word width.
Return Values~
Returns the given string wrapped at the specified length.
Examples~
Example #1 wordwrap() example
>
\n");
echo $newtext;
?>
<
The above example will output:
The quick brown fox
jumped over the lazy
dog.
Example #2 wordwrap() example
>
<
The above example will output:
A very
long
wooooooo
ooooord.
Example #3 wordwrap() example
>
<
The above example will output:
A very
long
woooooooooooooooooord.
and
something
See Also ¶
nl2br() - Inserts HTML line breaks before all newlines in a string
chunk_split() - Split a string into smaller chunks
add a note add a note
User Contributed Notes 20 notes
12 ju1ius ¶5 years ago~
Another solution to utf-8 safe wordwrap, unsing regular expressions.
Pretty good performance and works in linear time.
>
<
Of course don't forget to use preg_quote on the $width and $break
parameters if they come from untrusted input.
13 Dave Lozier - dave at fusionbb.com ¶11 years ago~
If you'd like to break long strings of text but avoid breaking html
you may find this useful. It seems to be working for me, hope it works
for you. Enjoy. :)
>
',$text);
$sizeof = sizeof($text_1);
for ($i=0; $i<$sizeof; ++$i) {
$text_2 = explode('<',$text_1[$i]);
if (!empty($text_2[0])) {
$new_text .= preg_replace('#([^\n\r .]{25})#i', '\\1 ', $text_2[0]);
}
if (!empty($text_2[1])) {
$new_text .= '<' . $text_2[1] . '>';
}
}
return $new_text;
}
?>
<
--------------------------------------------------------------------------------
from:
http://php.net/manual/en/function.fopen.php
*fopen*
+-------+~
| fopen |~
+-------+~
(PHP 4, PHP 5, PHP 7)
fopen — Opens file or URL
Description~
>
resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )
fopen() binds a named resource, specified by filename, to a stream.
<
Parameters~
filename
--------
If filename is of the form "scheme://...", it is assumed to be a URL
and PHP will search for a protocol handler (also known as a wrapper)
for that scheme. If no wrappers for that protocol are registered, PHP
will emit a notice to help you track potential problems in your script
and then continue as though filename specifies a regular file.
If PHP has decided that filename specifies a local file, then it will
try to open a stream on that file. The file must be accessible to PHP,
so you need to ensure that the file access permissions allow this
access. If you have enabled safe mode or open_basedir further
restrictions may apply.
If PHP has decided that filename specifies a registered protocol, and
that protocol is registered as a network URL, PHP will check to make
sure that allow_url_fopen is enabled. If it is switched off, PHP will
emit a warning and the fopen call will fail.
Note:
The list of supported protocols can be found in Supported Protocols
and Wrappers. Some protocols (also referred to as wrappers) support
context and/or php.ini options. Refer to the specific page for the
protocol in use for a list of options which can be set. (e.g. php.ini
value user_agent used by the http wrapper).
On the Windows platform, be careful to escape any backslashes used in
the path to the file, or use forward slashes.
>
<
mode
-----
The mode parameter specifies the type of access you require to the
stream. It may be any of the following:
A list of possible modes for fopen() using mode
mode Description
'r' Open for reading only; place the file pointer at the beginning of the file.
'r+' Open for reading and writing; place the file pointer at the
beginning of the file.
'w' Open for writing only; place the file pointer at the beginning
of the file and truncate the file to zero length. If the file does not
exist, attempt to create it.
'w+' Open for reading and writing; place the file pointer at the
beginning of the file and truncate the file to zero length. If the
file does not exist, attempt to create it.
'a' Open for writing only; place the file pointer at the end of
the file. If the file does not exist, attempt to create it. In this
mode, fseek() has no effect, writes are always appended.
'a+' Open for reading and writing; place the file pointer at the
end of the file. If the file does not exist, attempt to create it. In
this mode, fseek() only affects the reading position, writes are
always appended.
'x' Create and open for writing only; place the file pointer at
the beginning of the file. If the file already exists, the fopen()
call will fail by returning FALSE and generating an error of level
E_WARNING. If the file does not exist, attempt to create it. This is
equivalent to specifying O_EXCL|O_CREAT flags for the underlying
open(2) system call.
'x+' Create and open for reading and writing; otherwise it has the
same behavior as 'x'.
'c' Open the file for writing only. If the file does not exist, it
is created. If it exists, it is neither truncated (as opposed to 'w'),
nor the call to this function fails (as is the case with 'x'). The
file pointer is positioned on the beginning of the file. This may be
useful if it's desired to get an advisory lock (see flock()) before
attempting to modify the file, as using 'w' could truncate the file
before the lock was obtained (if truncation is desired, ftruncate()
can be used after the lock is requested).
'c+' Open the file for reading and writing; otherwise it has the
same behavior as 'c'.
'e' Set close-on-exec flag on the opened file descriptor. Only
available in PHP compiled on POSIX.1-2008 conform systems.
Note:
Different operating system families have different line-ending
conventions. When you write a text file and want to insert a line
break, you need to use the correct line-ending character(s) for your
operating system. Unix based systems use \n as the line ending
character, Windows based systems use \r\n as the line ending
characters and Macintosh based systems use \r as the line ending
character.
If you use the wrong line ending characters when writing your files,
you might find that other applications that open those files will
"look funny".
Windows offers a text-mode translation flag ('t') which will
transparently translate \n to \r\n when working with the file. In
contrast, you can also use 'b' to force binary mode, which will not
translate your data. To use these flags, specify either 'b' or 't' as
the last character of the mode parameter.
The default translation mode depends on the SAPI and version of PHP
that you are using, so you are encouraged to always specify the
appropriate flag for portability reasons. You should use the 't' mode
if you are working with plain-text files and you use \n to delimit
your line endings in your script, but expect your files to be readable
with applications such as notepad. You should use the 'b' in all other
cases.
If you do not specify the 'b' flag when working with binary files, you
may experience strange problems with your data, including broken image
files and strange problems with \r\n characters.
Note:
For portability, it is strongly recommended that you always use the
'b' flag when opening files with fopen().
Note:
Again, for portability, it is also strongly recommended that you
re-write code that uses or relies upon the 't' mode so that it uses
the correct line endings and 'b' mode instead.
use_include_path
----------------
The optional third use_include_path parameter can be set to '1' or
TRUE if you want to search for the file in the include_path, too.
context
-------
Note: Context support was added with PHP 5.0.0. For a description of
contexts, refer to Streams.
Return Values~
Returns a file pointer resource on success, or FALSE on error.
Errors/Exceptions~
If the open fails, an error of level E_WARNING is generated. You may
use @ to suppress this warning.
Changelog~
Version Description
7.0.16, 7.1.2 The 'e' option were added.
5.2.6 The 'c' and 'c+' options were added
4.3.2 As of PHP 4.3.2, the default mode is set to binary for all
platforms that distinguish between binary and text mode. If you are
having problems with your scripts after upgrading, try using the 't'
flag as a workaround until you have made your script more portable as
mentioned before
Examples~
Example #1 fopen() examples
>
<
Notes~
Warning
When using SSL, Microsoft IIS will violate the protocol by closing the
connection without sending a close_notify indicator. PHP will report
this as "SSL: Fatal Protocol Error" when you reach the end of the
data. To work around this, the value of error_reporting should be
lowered to a level that does not include warnings. PHP can detect
buggy IIS server software when you open the stream using the https://
wrapper and will suppress the warning. When using fsockopen() to
create an ssl:// socket, the developer is responsible for detecting
and suppressing this warning.
Note: When safe mode is enabled, PHP checks whether the directory in
which the script is operating has the same UID (owner) as the script
that is being executed.
Note:
If you are experiencing problems with reading and writing to files and
you're using the server module version of PHP, remember to make sure
that the files and directories you're using are accessible to the
server process.
Note:
This function may also succeed when filename is a directory. If you
are unsure whether filename is a file or a directory, you may need to
use the is_dir() function before calling fopen().
See Also~
Supported Protocols and Wrappers
|fclose|() - Closes an open file pointer
|fgets|() - Gets line from file pointer
|fread|() - Binary-safe file read
|fwrite|() - Binary-safe file write
|fsockopen|() - Open Internet or Unix domain socket connection
|file|() - Reads entire file into an array
|file_exists|() - Checks whether a file or directory exists
|is_readable|() - Tells whether a file exists and is readable
|stream_set_timeout|() - Set timeout period on a stream
|popen|() - Opens process file pointer
|stream_context_create|() - Creates a stream context
|umask|() - Changes the current umask
|SplFileObject|
User Contributed Notes 43 notes
57 chapman at worldtakeoverindustries dot com ¶5 years ago~
Note - using fopen in 'w' mode will NOT update the modification time
(filemtime) of a file like you may expect. You may want to issue a
touch() after writing and closing the file which update its
modification time. This may become critical in a caching situation, if
you intend to keep your hair.
10 php at delhelsa dot com ¶8 years ago~
With php 5.2.5 on Apache 2.2.4, accessing files on an ftp server with
fopen() or readfile() requires an extra forwardslash if an absolute
path is needed.
i.e., if a file called bullbes.txt is stored under /var/school/ on ftp
server example.com and you're trying to access it with user blossom
and password buttercup, the url would be:
ftp://blossom:buttercup@example.com//var/school/bubbles.txt
Note the two forwardslashes. It looks like the second one is needed so
the server won't interpret the path as relative to blossom's home on
townsville.
--------------------------------------------------------------------------------
*fclose*
+--------+~
| fclose |~
+--------+~
(PHP 4, PHP 5, PHP 7)
fclose — Closes an open file pointer
Description~
>
bool fclose ( resource $handle )
<
The file pointed to by handle is closed.
Parameters~
handle
------
The file pointer must be valid, and must point to a file successfully
opened by fopen() or fsockopen().
Return Values~
Returns TRUE on success or FALSE on failure.
Examples~
Example #1 A simple fclose() example
>
<
See Also~
|fopen|() - Opens file or URL
|fsockopen|() - Open Internet or Unix domain socket connection
User Contributed Notes 9 notes
7 jgotti ¶4 years ago~
In case you have some trouble to properly disconnect some client
streams opened with stream_socket_server / stream_select you should
give a try to stream_socket_shutdown.
>
<
6 jricher at jacquesricher dot com ¶12 years ago~
It is a GOOD_THING to check the return value from fclose(), as some
operating systems only flush file output on close, and can, therefore,
return an error from fclose(). You can catch severe data-eating errors
by doing this.
I learned this the hard way.
--------------------------------------------------------------------------------
*basename*
+----------+~
| basename |~
+----------+~
(PHP 4, PHP 5, PHP 7)
basename — Returns trailing name component of path
Description~
>
string basename ( string $path [, string $suffix ] )
<
Given a string containing the path to a file or directory, this
function will return the trailing name component.
Note:
basename() operates naively on the input string, and is not aware of
the actual filesystem, or path components such as "..".
Caution
basename() is locale aware, so for it to see the correct basename with
multibyte character paths, the matching locale must be set using the
setlocale() function.
Parameters~
path
-----
A path.
On Windows, both slash (/) and backslash (\) are used as directory
separator character. In other environments, it is the forward slash
(/).
suffix
------
If the name component ends in suffix this will also be cut off.
Return Values~
Returns the base name of the given path.
Examples~
Example #1 basename() example
>
<
The above example will output:
1) sudoers
2) sudoers.d
3) passwd
4) etc
5) .
6)
See Also~
|dirname|() - Returns a parent directory's path
|pathinfo|() - Returns information about a file path
23 stephane dot fidanza at gmail dot com ¶10 years ago~
Support of the $suffix parameter has changed between PHP4 and PHP5: in
PHP4, $suffix is removed first, and then the core basename is applied.
conversely, in PHP5, $suffix is removed AFTER applying core basename.
Example:
>
<
Result in PHP4: file
Result in PHP5: Texture)
9 (remove) dot nasretdinov at (remove) dot gmail dot com ¶8 years ago~
There is only one variant that works in my case for my Russian UTF-8
letters:
>
<
It is intented for UNIX servers
--------------------------------------------------------------------------------
*chgrp*
+-------+~
| chgrp |~
+-------+~
(PHP 4, PHP 5, PHP 7)
chgrp — Changes file group
Description~
>
bool chgrp ( string $filename , mixed $group )
<
Attempts to change the group of the file filename to group.
Only the superuser may change the group of a file arbitrarily; other
users may change the group of a file to any group of which that user
is a member.
Parameters~
filename
--------
Path to the file.
group
-----
A group name or number.
Return Values~
Returns TRUE on success or FALSE on failure.
Examples~
Example #1 Changing a file's group
>
<
Notes~
Note: This function will not work on remote files as the file to be
examined must be accessible via the server's filesystem.
Note: When safe mode is enabled, PHP checks whether the files or
directories being operated upon have the same UID (owner) as the
script that is being executed.
See Also~
|chown|() - Changes file owner
|chmod|() - Changes file mode
--------------------------------------------------------------------------------
*chmod*
+-------+~
| chmod |~
+-------+~
(PHP 4, PHP 5, PHP 7)
chmod — Changes file mode
Description~
>
bool chmod ( string $filename , int $mode )
<
Attempts to change the mode of the specified file to that given in
mode.
Parameters~
filename
--------
Path to the file.
mode
-----
Note that mode is not automatically assumed to be an octal value, so
to ensure the expected operation, you need to prefix mode with a zero
(0). Strings such as "g+w" will not work properly.
>
<
The mode parameter consists of three octal number components
specifying access restrictions for the owner, the user group in which
the owner is in, and to everybody else in this order. One component
can be computed by adding up the needed permissions for that target
user base. Number 1 means that you grant execute rights, number 2
means that you make the file writeable, number 4 means that you make
the file readable. Add up these numbers to specify needed rights. You
can also read more about modes on Unix systems with 'man 1 chmod' and
'man 2 chmod'.
>
<
Return Values~
Returns TRUE on success or FALSE on failure.
Notes~
Note:
The current user is the user under which PHP runs. It is probably not
the same user you use for normal shell or FTP access. The mode can be
changed only by user who owns the file on most systems.
Note: This function will not work on remote files as the file to be
examined must be accessible via the server's filesystem.
Note:
When safe mode is enabled, PHP checks whether the files or directories
you are about to operate on have the same UID (owner) as the script
that is being executed. In addition, you cannot set the SUID, SGID and
sticky bits.
See Also~
|chown|() - Changes file owner
|chgrp|() - Changes file group
|fileperms|() - Gets file permissions
|stat|() - Gives information about a file
User Contributed Notes 18 notes
42 MethodicalFool ¶6 years ago~
BEWARE, a couple of the examples in the comments suggest doing
something like this:
>
chmod(file_or_dir_name, intval($mode, 8));
<
However, if $mode is an integer then intval( ) won't modify it. So,
this code...
>
$mode = 644;
chmod('/tmp/test', intval($mode, 8));
<
...produces permissions that look like this:
1--w----r-T
Instead, use octdec( ), like this:
>
chmod(file_or_dir_name, octdec($mode));
<
See also: http://www.php.net/manual/en/function.octdec.php
23 Geoff W ¶7 years ago~
BEWARE using quotes around the second parameter...
If you use quotes eg
>
chmod (file, "0644");
<
php will not complain but will do an implicit conversion to an int
before running chmod. Unfortunately the implicit conversion doesn't
take into account the octal string so you end up with an integer
version 644, which is 1204 octal
11 pmichaud at pobox dot com ¶14 years ago~
In the previous post, stickybit avenger writes: Just a little hint. I
was once adwised to set the 'sticky bit', i.e. use 1777 as
chmod-value...
Note that in order to set the sticky bit on a file one must use
'01777' (oct) and not '1777' (dec) as the parameter to chmod:
>
<
Rule of thumb: always prefix octal mode values with a zero.
13 Anonymous ¶8 years ago~
Changes file mode recursive in $pathname to $filemode
>
<
16 masha at mail dot ru ¶11 years ago~
Usefull reference:
Value Permission Level
400 Owner Read
200 Owner Write
100 Owner Execute
40 Group Read
20 Group Write
10 Group Execute
4 Global Read
2 Global Write
1 Global Execute
(taken from http://www.onlamp.com/pub/a/php/2003/02/06/php_foundations.html)
--------------------------------------------------------------------------------
*chown*
+-------+~
| chown |~
+-------+~
(PHP 4, PHP 5, PHP 7)
chown — Changes file owner
Description~
>
bool chown ( string $filename , mixed $user )
<
Attempts to change the owner of the file filename to user user. Only
the superuser may change the owner of a file.
Parameters~
filename
--------
Path to the file.
user
-----
A user name or number.
Return Values~
Returns TRUE on success or FALSE on failure.
Examples~
Example #1 Simple chown() usage
>
<
The above example will output something similar to:
Array
(
[name] => root
[passwd] => x
[uid] => 0
[gid] => 0
[gecos] => root
[dir] => /root
[shell] => /bin/bash
)
Notes~
Note: This function will not work on remote files as the file to be
examined must be accessible via the server's filesystem.
Note: When safe mode is enabled, PHP checks whether the files or
directories being operated upon have the same UID (owner) as the
script that is being executed.
See Also~
|chmod|() - Changes file mode
|chgrp|() - Changes file group
--------------------------------------------------------------------------------
*clearstatcache*
+----------------+~
| clearstatcache |~
+----------------+~
(PHP 4, PHP 5, PHP 7)
clearstatcache — Clears file status cache
Description~
>
void clearstatcache ([ bool $clear_realpath_cache = false [, string $filename ]] )
<
When you use stat(), lstat(), or any of the other functions listed in
the affected functions list (below), PHP caches the information those
functions return in order to provide faster performance. However, in
certain cases, you may want to clear the cached information. For
instance, if the same file is being checked multiple times within a
single script, and that file is in danger of being removed or changed
during that script's operation, you may elect to clear the status
cache. In these cases, you can use the clearstatcache() function to
clear the information that PHP caches about a file.
You should also note that PHP doesn't cache information about
non-existent files. So, if you call file_exists() on a file that
doesn't exist, it will return FALSE until you create the file. If you
create the file, it will return TRUE even if you then delete the file.
However unlink() clears the cache automatically.
Note:
This function caches information about specific filenames, so you only
need to call clearstatcache() if you are performing multiple
operations on the same filename and require the information about that
particular file to not be cached. Affected functions include stat(),
lstat(), file_exists(), is_writable(), is_readable(), is_executable(),
is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(),
fileinode(), filegroup(), fileowner(), filesize(), filetype(), and
fileperms().
Parameters~
clear_realpath_cache
--------------------
Whether to clear the realpath cache or not.
filename
--------
Clear the realpath and the stat cache for a specific filename only;
only used if clear_realpath_cache is TRUE.
Return Values~
No value is returned.
Changelog~
Version Description
5.3.0 Added optional clear_realpath_cache and filename parameters.
Examples~
Example #1 clearstatcache() example
>
<
The above example will output something similar to:
UID @ Sun, 12 Oct 2008 20:48:28 +0100: root
UID @ Sun, 12 Oct 2008 20:48:28 +0100: root
UID @ Sun, 12 Oct 2008 20:48:28 +0100: ross
User Contributed Notes 3 notes
15 matt_m at me dot com ¶5 years ago~
unlink() does not clear the cache if you are performing file_exists()
on a remote file like:
>
<
In this case, even after you unlink() successfully, you must call clearstatcache().
>
<
file_exists() then properly returns false.
--------------------------------------------------------------------------------
*copy*
+------+~
| copy |~
+------+~
(PHP 4, PHP 5, PHP 7)
copy — Copies file
Description~
>
bool copy ( string $source , string $dest [, resource $context ] )
<
Makes a copy of the file source to dest.
If you wish to move a file, use the rename() function.
Parameters~
source
------
Path to the source file.
dest
-----
The destination path. If dest is a URL, the copy operation may fail if
the wrapper does not support overwriting of existing files.
Warning
If the destination file already exists, it will be overwritten.
context
A valid context resource created with stream_context_create().
Return Values~
Returns TRUE on success or FALSE on failure.
Changelog~
Version Description
5.3.4 Changed the context parameter to actually have an effect.
Previously, any context was ignored.
5.3.0 Added context support.
4.3.0 Both source and dest may now be URLs if the "fopen wrappers"
have been enabled. See fopen() for more details.
Examples~
Example #1 copy() example
>
<
See Also~
|move_uploaded_file|() - Moves an uploaded file to a new location
|rename|() - Renames a file or directory
The section of the manual about |handling_file_uploads|
108 simonr_at_orangutan_dot_co_dot_uk ¶12 years ago~
Having spent hours tacking down a copy() error: Permission denied ,
(and duly worrying about chmod on winXP) , its worth pointing out that
the 'destination' needs to contain the actual file name ! --- NOT just
the path to the folder you wish to copy into.......
DOH !
hope this saves somebody hours of fruitless debugging
56 cooper at asu dot ntu-kpi dot kiev dot ua ¶11 years ago~
It take me a long time to find out what the problem is when i've got
an error on copy(). It DOESN'T create any directories. It only copies
to existing path. So create directories before. Hope i'll help,
46 steve a h ¶8 years ago~
Don't forget; you can use copy on remote files, rather than doing
messy fopen stuff. e.g.
>
\n".$errors['message'];
} else {
echo "File copied from remote!";
}
?>
<
3 hugo_2000 at gmx dot at ¶1 year ago~
If you try to copy a file to itself - e.g. if the target directory is
just a symlink to the source directory - copy will return false. just
like on the command line.
15 absorbentshoulderman at gmail dot com ¶4 years ago~
A nice simple trick if you need to make sure the folder exists first:
>
<
That simple.
22 gimmicklessgpt at gmail dot com ¶7 years ago~
Here's a simple recursive function to copy entire directories
Note to do your own check to make sure the directory exists that you
first call it on.
>
<
10 promaty at gmail dot com ¶5 years ago~
Here is a simple script that I use for removing and copying non-empty
directories. Very useful when you are not sure what is the type of a
file.
I am using these for managing folders and zip archives for my website
plugins.
>
<
Cheers!
--------------------------------------------------------------------------------
*handling_file_uploads*
+-----------------------+~
| Handling file uploads |~
+-----------------------+~
Table of Contents~
|POST_method_uploads|
|Error_Messages_Explained|
|Common_Pitfalls|
|Uploading_multiple_files|
|PUT_method_support|
251 CertaiN ¶3 years ago~
You'd better check $_FILES structure and values throughly. The
following code cannot cause any errors absolutely.
Example:
>
1000000) {
throw new RuntimeException('Exceeded filesize limit.');
}
// DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
// Check MIME Type by yourself.
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
$finfo->file($_FILES['upfile']['tmp_name']),
array(
'jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
),
true
)) {
throw new RuntimeException('Invalid file format.');
}
// You should name it uniquely.
// DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
// On this example, obtain safe unique name from its binary data.
if (!move_uploaded_file(
$_FILES['upfile']['tmp_name'],
sprintf('./uploads/%s.%s',
sha1_file($_FILES['upfile']['tmp_name']),
$ext
)
)) {
throw new RuntimeException('Failed to move uploaded file.');
}
echo 'File is uploaded successfully.';
} catch (RuntimeException $e) {
echo $e->getMessage();
}
?>
<
22 xmontero at dsitelecom dot com ¶5 years ago~
If "large files" (ie: 50 or 100 MB) fail, check this:
It may happen that your outgoing connection to the server is slow, and
it may timeout not the "execution time" but the "input time", which
for example in our system defaulted to 60s. In our case a large upload
could take 1 or 2 hours.
Additionally we had "session settings" that should be preserved after
upload.
1) You might want review those ini entries:
* session.gc_maxlifetime
* max_input_time
* max_execution_time
* upload_max_filesize
* post_max_size
2) Still fails? Caution, not all are changeable from the script
itself. ini_set() might fail to override.
More info here:
http://www.php.net/manual/es/ini.list.php
You can see that the "upload_max_filesize", among others, is
PHP_INI_PERDIR and not PHP_INI_ALL. This invalidates to use ini_set():
http://www.php.net/manual/en/configuration.changes.modes.php
Use .htaccess instead.
3) Still fails?. Just make sure you enabled ".htaccess" to overwrite
your php settings. This is made in the apache file. You need at least
AllowOverride Options.
See this here: http://www.php.net/manual/en/configuration.changes.php
You will necessarily allow this manually in the case your master files come with AllowOverride None.
Conclussion:
Depending on the system, to allow "large file uploads" you must go up
and up and up and touch your config necessarily up to the apache
config.
Sample files:
These work for me, for 100MB uploads, lasting 2 hours:
In apache-virtual-host:
-----------------------------------------------------------
AllowOverride Options
-----------------------------------------------------------
In .htaccess:
-----------------------------------------------------------
php_value session.gc_maxlifetime 10800
php_value max_input_time 10800
php_value max_execution_time 10800
php_value upload_max_filesize 110M
php_value post_max_size 120M
-----------------------------------------------------------
In the example,
- As I last 1 to 2 hours, I allow 3 hours (3600x3)
- As I need 100MB, I allow air above for the file (110M) and a bit
more for the whole post (120M).
12 ceo at l-i-e dot com ¶11 years ago~
Using /var/www/uploads in the example code is just criminal, imnsho.
One should *NOT* upload untrusted files into your web tree, on any
server.
Nor should any directory within your web tree have permissions
sufficient for an upload to succeed, on a shared server. Any other
user on that shared server could write a PHP script to dump anything
they want in there!
The $_FILES['userfile']['type'] is essentially USELESS.
A. Browsers aren't consistent in their mime-types, so you'll never
catch all the possible combinations of types for any given file
format.
B. It can be forged, so it's crappy security anyway.
One's code should INSPECT the actual file to see if it looks kosher.
For example, images can quickly and easily be run through imagegetsize
and you at least know the first N bytes LOOK like an image. That
doesn't guarantee it's a valid image, but it makes it much less likely
to be a workable security breaching file.
For Un*x based servers, one could use exec and 'file' command to see
if the Operating System thinks the internal contents seem consistent
with the data type you expect.
I've had trouble in the past with reading the '/tmp' file in a file
upload. It would be nice if PHP let me read that file BEFORE I tried
to move_uploaded_file on it, but PHP won't, presumably under the
assumption that I'd be doing something dangerous to read an untrusted
file. Fine. One should move the uploaded file to some staging
directory. Then you check out its contents as thoroughly as you can.
THEN, if it seems kosher, move it into a directory outside your web
tree. Any access to that file should be through a PHP script which
reads the file. Putting it into your web tree, even with all the
checks you can think of, is just too dangerous, imnsho.
There are more than a few User Contributed notes here with naive (bad)
advice. Be wary.
13 jan at lanteraudio dot nl ¶4 years ago~
Also stumbled on the max_file_size problem, in particular getting no
response, no error whatsoever when uploading a file bigger than the
set upload_max_filesize.
I found that it's not the upload_max_filesize setting, but instead the
post_max_size setting causing this no response issue. So if you set
post_max_size way larger than upload_max_filesize, at least you are
likely to get an error response when filesize exceeds
upload_max_filesize but is still within the limits of post_max_size.
Hope this helps anyone.
5 myko AT blue needle DOT com ¶11 years ago~
Just a quick note that there's an issue with Apache, the MAX_FILE_SIZE
hidden form field, and zlib.output_compression = On. Seems that the
browser continues to post up the entire file, even though PHP throws
the MAX_FILE_SIZE error properly. Turning zlib compression to OFF
seems to solve the issue. Don't have time to dig in and see who's at
fault, but wanted to save others the hassle of banging their head on
this one.
12 svenr at selfhtml dot org ¶10 years ago~
Clarification on the MAX_FILE_SIZE hidden form field:
PHP has the somewhat strange feature of checking multiple "maximum
file sizes".
The two widely known limits are the php.ini settings "post_max_size"
and "upload_max_size", which in combination impose a hard limit on the
maximum amount of data that can be received.
In addition to this PHP somehow got implemented a soft limit feature.
It checks the existance of a form field names "max_file_size" (upper
case is also OK), which should contain an integer with the maximum
number of bytes allowed. If the uploaded file is bigger than the
integer in this field, PHP disallows this upload and presents an error
code in the $_FILES-Array.
The PHP documentation also makes (or made - see bug #40387 -
http://bugs.php.net/bug.php?id=40387) vague references to "allows
browsers to check the file size before uploading". This, however, is
not true and has never been. Up til today there has never been a RFC
proposing the usage of such named form field, nor has there been a
browser actually checking its existance or content, or preventing
anything. The PHP documentation implies that a browser may alert the
user that his upload is too big - this is simply wrong.
Please note that using this PHP feature is not a good idea. A form
field can easily be changed by the client. If you have to check the
size of a file, do it conventionally within your script, using a
script-defined integer, not an arbitrary number you got from the HTTP
client (which always must be mistrusted from a security standpoint).
9 jedi_aka at yahoo dot com ¶10 years ago~
For those of you trying to make the upload work with IIS on windows
XP/2000/XP Media and alike here is a quick todo.
1) Once you have created subdirectories "uploads/" in the same
directory wher you code is running use the code from oportocala above
and to make absolutely sure sure that the file you are trying to right
is written under that folder. ( I recomend printing it using echo
$uploadfile; )
2) In windows explorer browse to the upload directory created above
and share it. To do that execute the following substeps.
a) Right click the folder click "sharing and security..."
b) Check 'Share this folder on the network'
c) Check 'Allow network users to change my files' ( THIS STEP IS VERY IMPORTANT )
d) click 'ok' or 'apply'
3) you can then go in the IIS to set read and write permissions for
it. To do that execute the followin substeps.
a) Open IIS (Start/Controp Panel (classic View)/ Admistrative
tools/Internet Information Service
b) Browse to your folder (the one we created above)
c) right click and select properties.
d) in the Directory tab, make sure, READ, WRITE, AND DIRECTORY
BROWSING are checked.
e) For the security freaks out there, You should also make sure
that 'execute permissions:' are set to Script only or lower (DO NOT
SET IT TO 'script and executable)'( that is because someone could
upload a script to your directory and run it. And, boy, you do not
want that to happen).
there U go.
Send me feed back it if worked for you or not so that I can update the todo.
jedi_aka@yahoo.com
PS: BIG thanks to oportocala
11 info at levaravel dot com ¶8 years ago~
A little codesnippet which returns a filesize in a more legible format.
>
0.9){
$filesize = $filesize / $decr;
$step++;
}
return round($filesize,2).' '.$prefix[$step];
} else {
return 'NaN';
}
}
?>
<
14 keith at phpdiary dot org ¶11 years ago~
Caution: *DO NOT* trust $_FILES['userfile']['type'] to verify the
uploaded filetype; if you do so your server could be compromised.
I'll show you why below:
The manual (if you scroll above) states: $_FILES['userfile']['type'] -
The mime type of the file, if the browser provided this information.
An example would be "image/gif".
Be reminded that this mime type can easily be faked as PHP doesn't go
very far in verifying whether it really is what the end user reported!
So, someone could upload a nasty .php script as an "image/gif" and
execute the url to the "image".
My best bet would be for you to check the extension of the file and
using exif_imagetype() to check for valid images. Many people have
suggested the use of getimagesize() which returns an array if the file
is indeed an image and false otherwise, but exif_imagetype() is much
faster. (the manual says it so)
--------------------------------------------------------------------------------
*POST_method_uploads*
+---------------------+~
| POST method uploads |~
+---------------------+~
This feature lets people upload both text and binary files. With PHP's
authentication and file manipulation functions, you have full control
over who is allowed to upload and what is to be done with the file
once it has been uploaded.
PHP is capable of receiving file uploads from any RFC-1867 compliant
browser.
Note: Related Configurations Note
See also the file_uploads, upload_max_filesize, upload_tmp_dir,
post_max_size and max_input_time directives in php.ini PHP also
supports PUT-method file uploads as used by Netscape Composer and
W3C's Amaya clients. See the PUT Method Support for more details.
Example #1 File Upload Form
A file upload screen can be built by creating a special form which
looks something like this:
>
<
The __URL__ in the above example should be replaced, and point to a
PHP file.
The MAX_FILE_SIZE hidden field (measured in bytes) must precede the
file input field, and its value is the maximum filesize accepted by
PHP. This form element should always be used as it saves users the
trouble of waiting for a big file being transferred only to find that
it was too large and the transfer failed. Keep in mind: fooling this
setting on the browser side is quite easy, so never rely on files with
a greater size being blocked by this feature. It is merely a
convenience feature for users on the client side of the application.
The PHP settings (on the server side) for maximum-size, however,
cannot be fooled.
Note:
Be sure your file upload form has attribute
enctype="multipart/form-data" otherwise the file upload will not work.
The global $_FILES will contain all the uploaded file information. Its
contents from the example form is as follows. Note that this assumes
the use of the file upload name userfile, as used in the example
script above. This can be any name.
$_FILES['userfile']['name']
The original name of the file on the client machine.
$_FILES['userfile']['type']
The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.
$_FILES['userfile']['size']
The size, in bytes, of the uploaded file.
$_FILES['userfile']['tmp_name']
The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES['userfile']['error']
The error code associated with this file upload.
Files will, by default be stored in the server's default temporary
directory, unless another location has been given with the
upload_tmp_dir directive in php.ini. The server's default directory
can be changed by setting the environment variable TMPDIR in the
environment in which PHP runs. Setting it using putenv() from within a
PHP script will not work. This environment variable can also be used
to make sure that other operations are working on uploaded files, as
well.
Example #2 Validating file uploads
See also the function entries for is_uploaded_file() and
move_uploaded_file() for further information. The following example
will process the file upload that came from a form.
>
';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "";
?>
<
The PHP script which receives the uploaded file should implement
whatever logic is necessary for determining what should be done with
the uploaded file. You can, for example, use the
$_FILES['userfile']['size'] variable to throw away any files that are
either too small or too big. You could use the
$_FILES['userfile']['type'] variable to throw away any files that
didn't match a certain type criteria, but use this only as first of a
series of checks, because this value is completely under the control
of the client and not checked on the PHP side. Also, you could use
$_FILES['userfile']['error'] and plan your logic according to the
error codes. Whatever the logic, you should either delete the file
from the temporary directory or move it elsewhere.
If no file is selected for upload in your form, PHP will return
$_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name']
as none.
The file will be deleted from the temporary directory at the end of
the request if it has not been moved away or renamed.
Example #3 Uploading array of files
PHP supports HTML array feature even with files.
>
$error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = basename($_FILES["pictures"]["name"][$key]);
move_uploaded_file($tmp_name, "data/$name");
}
}
?>
<
File upload progress bar can be implemented using Session Upload
Progress.
User Contributed Notes 15 notes
255 Anonymous ¶2 years ago~
For the love of god, don't do what michael suggests in
http://php.net/manual/en/features.file-upload.post-method.php#94973 or
you will be instantly pwned by someone uploading a php-shell to your
script dir.
When the mods come to delete this note for violating the
don't-refer-to-another-note rule, please please /please/ delete
michael's note too.
40 daevid at daevid dot com ¶7 years ago~
I think the way an array of attachments works is kind of cumbersome.
Usually the PHP guys are right on the money, but this is just
counter-intuitive. It should have been more like:
Array
(
[0] => Array
(
[name] => facepalm.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpn3FmFr
[error] => 0
[size] => 15476
)
[1] => Array
(
[name] =>
[type] =>
[tmp_name] =>
[error] => 4
[size] =>
)
)
and not this
Array
(
[name] => Array
(
[0] => facepalm.jpg
[1] =>
)
[type] => Array
(
[0] => image/jpeg
[1] =>
)
[tmp_name] => Array
(
[0] => /tmp/phpn3FmFr
[1] =>
)
[error] => Array
(
[0] => 0
[1] => 4
)
[size] => Array
(
[0] => 15476
[1] => 0
)
)
Anyways, here is a fuller example than the sparce one in the documentation above:
>
$error)
{
$tmp_name = $_FILES["attachment"]["tmp_name"][$key];
if (!$tmp_name) continue;
$name = basename($_FILES["attachment"]["name"][$key]);
if ($error == UPLOAD_ERR_OK)
{
if ( move_uploaded_file($tmp_name, "/tmp/".$name) )
$uploaded_array[] .= "Uploaded file '".$name."'. \n";
else
$errormsg .= "Could not move uploaded file '".$tmp_name."' to '".$name."' \n";
}
else $errormsg .= "Upload error. [".$error."] on file '".$name."' \n";
}
?>
<
6 mpyw ¶9 months ago~
Do not use Coreywelch or Daevid's way, because their methods can
handle only within two-dimensional structure. $_FILES can consist of
any hierarchy, such as 3d or 4d structure.
The following example form breaks their codes:
>
<
As the solution, you should use PSR-7 based zendframework/zend-diactoros.
GitHub:
https://github.com/zendframework/zend-diactoros
Example:
>
getMethod() !== 'POST') {
http_response_code(405);
exit('Use POST method.');
}
$uploaded_files = $request->getUploadedFiles();
if (
!isset($uploaded_files['files']['x']['y']['z']) ||
!$uploaded_files['files']['x']['y']['z'] instanceof UploadedFileInterface
) {
http_response_code(400);
exit('Invalid request body.');
}
$file = $uploaded_files['files']['x']['y']['z'];
if ($file->getError() !== UPLOAD_ERR_OK) {
http_response_code(400);
exit('File uploading failed.');
}
$file->moveTo('/path/to/new/file');
?>
<
14 eslindsey at gmail dot com ¶8 years ago~
Also note that since MAX_FILE_SIZE hidden field is supplied by the
browser doing the submitting, it is easily overridden from the
clients' side. You should always perform your own examination and
error checking of the file after it reaches you, instead of relying on
information submitted by the client. This includes checks for file
size (always check the length of the actual data versus the reported
file size) as well as file type (the MIME type submitted by the
browser can be inaccurate at best, and intentionally set to an
incorrect value at worst).
8 coreywelch+phpnet at gmail dot com ¶1 year ago~
The documentation doesn't have any details about how the HTML array
feature formats the $_FILES array.
Example $_FILES array:
For single file -
Array
(
[document] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
)
Multi-files with HTML array feature -
Array
(
[documents] => Array
(
[name] => Array
(
[0] => sample-file.doc
[1] => sample-file.doc
)
[type] => Array
(
[0] => application/msword
[1] => application/msword
)
[tmp_name] => Array
(
[0] => /tmp/path/phpVGCDAJ
[1] => /tmp/path/phpVGCDAJ
)
[error] => Array
(
[0] => 0
[1] => 0
)
[size] => Array
(
[0] => 0
[1] => 0
)
)
)
The problem occurs when you have a form that uses both single file and
HTML array feature. The array isn't normalized and tends to make
coding for it really sloppy. I have included a nice method to
normalize the $_FILES array.
>
$file) {
if (!is_array($file['name'])) {
$normalized_array[$index][] = $file;
continue;
}
foreach($file['name'] as $idx => $name) {
$normalized_array[$index][$idx] = [
'name' => $name,
'type' => $file['type'][$idx],
'tmp_name' => $file['tmp_name'][$idx],
'error' => $file['error'][$idx],
'size' => $file['size'][$idx]
];
}
}
return $normalized_array;
}
?>
<
The following is the output from the above method.
Array
(
[document] => Array
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
)
[documents] => Array
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
[1] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
)
)
--------------------------------------------------------------------------------
*Error_Messages_Explained*
+--------------------------+~
| Error Messages Explained |~
+--------------------------+~
PHP returns an appropriate error code along with the file array. The
error code can be found in the error segment of the file array that is
created during the file upload by PHP. In other words, the error might
be found in $_FILES['userfile']['error'].
UPLOAD_ERR_OK
Value: 0; There is no error, the file uploaded with success.
UPLOAD_ERR_INI_SIZE
Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
UPLOAD_ERR_FORM_SIZE
Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
UPLOAD_ERR_PARTIAL
Value: 3; The uploaded file was only partially uploaded.
UPLOAD_ERR_NO_FILE
Value: 4; No file was uploaded.
UPLOAD_ERR_NO_TMP_DIR
Value: 6; Missing a temporary folder. Introduced in PHP 5.0.3.
UPLOAD_ERR_CANT_WRITE
Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.
UPLOAD_ERR_EXTENSION
Value: 8; A PHP extension stopped the file upload. PHP does not
provide a way to ascertain which extension caused the file upload to
stop; examining the list of loaded extensions with phpinfo() may help.
Introduced in PHP 5.2.0.
User Contributed Notes 17 notes
119 Anonymous ¶8 years ago~
[EDIT BY danbrown AT php DOT net: This code is a fixed version of a
note originally submitted by (Thalent, Michiel Thalen) on
04-Mar-2009.]
This is a handy exception to use when handling upload errors:
>
codeToMessage($code);
parent::__construct($message, $code);
}
private function codeToMessage($code)
{
switch ($code) {
case UPLOAD_ERR_INI_SIZE:
$message = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
break;
case UPLOAD_ERR_FORM_SIZE:
$message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
break;
case UPLOAD_ERR_PARTIAL:
$message = "The uploaded file was only partially uploaded";
break;
case UPLOAD_ERR_NO_FILE:
$message = "No file was uploaded";
break;
case UPLOAD_ERR_NO_TMP_DIR:
$message = "Missing a temporary folder";
break;
case UPLOAD_ERR_CANT_WRITE:
$message = "Failed to write file to disk";
break;
case UPLOAD_ERR_EXTENSION:
$message = "File upload stopped by extension";
break;
default:
$message = "Unknown upload error";
break;
}
return $message;
}
}
// Use
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
//uploading successfully done
} else {
throw new UploadException($_FILES['file']['error']);
}
?>
<
69 Viktor ¶2 years ago~
Update to Adams old comment.
This is probably useful to someone.
>
'There is no error, the file uploaded with success',
1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3 => 'The uploaded file was only partially uploaded',
4 => 'No file was uploaded',
6 => 'Missing a temporary folder',
7 => 'Failed to write file to disk.',
8 => 'A PHP extension stopped the file upload.',
);
<
69 adam at gotlinux dot us ¶11 years ago~
This is probably useful to someone.
>
"There is no error, the file uploaded with success",
1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
3=>"The uploaded file was only partially uploaded",
4=>"No file was uploaded",
6=>"Missing a temporary folder"
);
?>
<
28 stephen at poppymedia dot co dot uk ¶11 years ago~
if post is greater than post_max_size set in php.ini
$_FILES and $_POST will return empty
10 Jeff Miner mrjminer AT gmail DOT com ¶6 years ago~
One thing that is annoying is that the way these constant values are
handled requires processing no error with the equality, which wastes a
little bit of space. Even though "no error" is 0, which typically
evaluates to "false" in an if statement, it will always evaluate to
true in this context.
So, instead of this:
-----
>
<
-----
You have to do this:
-----
>
<
-----
Also, ctype_digit fails, but is_int works. If you're wondering... no,
it doesn't make any sense.
To Schoschie:
You ask the question: Why make stuff complicated when you can make it
easy? I ask the same question since the version of the code you /
Anonymous / Thalent (per danbrown) have posted is unnecessary overhead
and would result in a function call, as well as a potentially lengthy
switch statement. In a loop, that would be deadly... try this
instead:
-----
>
'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
'The uploaded file was only partially uploaded.',
'No file was uploaded.',
6=>'Missing a temporary folder.',
'Failed to write file to disk.',
'A PHP extension stopped the file upload.'
);
// Outside a loop...
if($_FILES['userfile']['error']==0) {
// process
} else {
$error_message = $error_types[$_FILES['userfile']['error']];
// do whatever with the error message
}
// In a loop...
for($x=0,$y=count($_FILES['userfile']['error']);$x<$y;++$x) {
if($_FILES['userfile']['error'][$x]==0) {
// process
} else {
$error_message = $error_types[$_FILES['userfile']['error'][$x]];
// Do whatever with the error message
}
}
// When you're done... if you aren't doing all of this in a function that's about to end / complete all the processing and want to reclaim the memory
unset($error_types);
?>
<
--------------------------------------------------------------------------------
*Common_Pitfalls*
+-----------------+~
| Common Pitfalls |~
+-----------------+~
The MAX_FILE_SIZE item cannot specify a file size greater than the
file size that has been set in the upload_max_filesize in the php.ini
file. The default is 2 megabytes.
If a memory limit is enabled, a larger memory_limit may be needed.
Make sure you set memory_limit large enough.
If max_execution_time is set too small, script execution may be
exceeded by the value. Make sure you set max_execution_time large
enough.
Note: max_execution_time only affects the execution time of the script
itself. Any time spent on activity that happens outside the execution
of the script such as system calls using system(), the sleep()
function, database queries, time taken by the file upload process,
etc. is not included when determining the maximum time that the script
has been running.
Warning
max_input_time sets the maximum time, in seconds, the script is
allowed to receive input; this includes file uploads. For large or
multiple files, or users on slower connections, the default of 60
seconds may be exceeded.
If post_max_size is set too small, large files cannot be uploaded.
Make sure you set post_max_size large enough.
Since PHP 5.2.12, the max_file_uploads configuration setting controls
the maximum number of files that can uploaded in one request. If more
files are uploaded than the limit, then $_FILES will stop processing
files once the limit is reached. For example, if max_file_uploads is
set to 10, then $_FILES will never contain more than 10 items.
Not validating which file you operate on may mean that users can
access sensitive information in other directories.
Please note that the CERN httpd seems to strip off everything starting
at the first whitespace in the content-type mime header it gets from
the client. As long as this is the case, CERN httpd will not support
the file upload feature.
Due to the large amount of directory listing styles we cannot
guarantee that files with exotic names (like containing spaces) are
handled properly.
A developer may not mix normal input fields and file upload fields in
the same form variable (by using an input name like foo[]).
--------------------------------------------------------------------------------
*Uploading_multiple_files*
+--------------------------+~
| Uploading multiple files |~
+--------------------------+~
Multiple files can be uploaded using different name for input.
It is also possible to upload multiple files simultaneously and have
the information organized automatically in arrays for you. To do so,
you need to use the same array submission syntax in the HTML form as
you do with multiple selects and checkboxes:
Example #1 Uploading multiple files
>
<
When the above form is submitted, the arrays $_FILES['userfile'],
$_FILES['userfile']['name'], and $_FILES['userfile']['size'] will be
initialized (as well as in $HTTP_POST_FILES for PHP versions prior to
4.1.0). When register_globals is on, globals for uploaded files are
also initialized. Each of these will be a numerically indexed array of
the appropriate values for the submitted files.
For instance, assume that the filenames /home/test/review.html and
/home/test/xwp.out are submitted. In this case,
$_FILES['userfile']['name'][0] would contain the value review.html,
and $_FILES['userfile']['name'][1] would contain the value xwp.out.
Similarly, $_FILES['userfile']['size'][0] would contain review.html's
file size, and so forth.
$_FILES['userfile']['name'][0], $_FILES['userfile']['tmp_name'][0],
$_FILES['userfile']['size'][0], and $_FILES['userfile']['type'][0] are
also set.
Warning
Since PHP 5.2.12, the max_file_uploads configuration setting acts as a
limit on the number of files that can be uploaded in one request. You
will need to ensure that your form does not try to upload more files
in one request than this limit.
207 phpuser at gmail dot com ¶11 years ago~
When uploading multiple files, the $_FILES variable is created in the
form:
Array
(
[name] => Array
(
[0] => foo.txt
[1] => bar.txt
)
[type] => Array
(
[0] => text/plain
[1] => text/plain
)
[tmp_name] => Array
(
[0] => /tmp/phpYzdqkD
[1] => /tmp/phpeEwEWG
)
[error] => Array
(
[0] => 0
[1] => 0
)
[size] => Array
(
[0] => 123
[1] => 456
)
)
I found it made for a little cleaner code if I had the uploaded files
array in the form
Array
(
[0] => Array
(
[name] => foo.txt
[type] => text/plain
[tmp_name] => /tmp/phpYzdqkD
[error] => 0
[size] => 123
)
[1] => Array
(
[name] => bar.txt
[type] => text/plain
[tmp_name] => /tmp/phpeEwEWG
[error] => 0
[size] => 456
)
)
I wrote a quick function that would convert the $_FILES array to the
cleaner (IMHO) array.
>
<
Now I can do the following:
>
<
36 wizzard351 at yahoo dot com ¶3 years ago~
This is also needed for elements.
So, if you have an input element like this:
This should be written as
else you'll only be able to get one of the files.
10 Corey Ballou ¶7 years ago~
Here is a function to fix the indices of a multi-dimensional for
easier parsing when dealing with file uploads. It takes a single
$_FILES field array as a parameter and separates each individual
uploaded file by numeric key. This allows for iterating like:
>
$file) {
// should output array with indices name, type, tmp_name, error, size
var_dump($file);
}
?>
<
Here's the code:
>
1, 'type' => 1, 'tmp_name' => 1, 'error' => 1, 'size' => 1);
foreach ($files as $key => $part) {
// only deal with valid keys and multiple files
$key = (string) $key;
if (isset($names[$key]) && is_array($part)) {
foreach ($part as $position => $value) {
$files[$position][$key] = $value;
}
// remove old key reference
unset($files[$key]);
}
}
}
?>
<
12 timspeelman at live dot nl ¶5 years ago~
The cleanest way to rearrange the $_FILES
>
$all ){
foreach( $all as $i => $val ){
$new[$i][$key] = $val;
}
}
return $new;
}
?>
<
--------------------------------------------------------------------------------
*PUT_method_support*
+--------------------+~
| PUT method support |~
+--------------------+~
PHP provides support for the HTTP PUT method used by some clients to
store files on a server. PUT requests are much simpler than a file
upload using POST requests and they look something like this:
PUT /path/filename.html HTTP/1.1
This would normally mean that the remote client would like to save the
content that follows as: /path/filename.html in your web tree. It is
obviously not a good idea for Apache or PHP to automatically let
everybody overwrite any files in your web tree. So, to handle such a
request you have to first tell your web server that you want a certain
PHP script to handle the request. In Apache you do this with the
Script directive. It can be placed almost anywhere in your Apache
configuration file. A common place is inside a block or
perhaps inside a block. A line like this would do the
trick:
Script PUT /put.php
This tells Apache to send all PUT requests for URIs that match the
context in which you put this line to the put.php script. This
assumes, of course, that you have PHP enabled for the .php extension
and PHP is active. The destination resource for all PUT requests to
this script has to be the script itself, not a filename the uploaded
file should have.
With PHP you would then do something like the following in your
put.php. This would copy the contents of the uploaded file to the file
myputfile.ext on the server. You would probably want to perform some
checks and/or authenticate the user before performing this file copy.
Example #1 Saving HTTP PUT files
>
<
User Contributed Notes 7 notes
24 micronix at gmx dot net ¶6 years ago~
Hello PHP World After many Hours of worryness :=)
I have found the Solution for Resume or Pause Uploads
In this Code Snippet it is the Server Side not Client on any Desktop
Programm you must use byte ranges to calculate the uploaded bytes and
missing of total bytes.
Here the PHP Code
>
getMessage(), "\n";
}
?>
<
--------------------------------------------------------------------------------
*delete*
+--------+~
| delete |~
+--------+~
delete — See unlink() or unset()
Description~
This is a dummy manual entry to satisfy those people who are looking
for unlink() or unset() in the wrong place.
See Also~
|unlink|() - Deletes a file
|unset|() - Unset a given variable
User Contributed Notes 1 note
30 Edward Morgan ¶3 years ago~
Unlink refers to the underlying UNIX command, unlink, which removes
the symbolic or hard link to the file, not necessarily the file
itself. The file is only removed when all links to the file are
removed.
--------------------------------------------------------------------------------
*dirname*
+---------+~
| dirname |~
+---------+~
(PHP 4, PHP 5, PHP 7)
dirname — Returns a parent directory's path
Description~
>
string dirname ( string $path [, int $levels = 1 ] )
<
Given a string containing the path of a file or directory, this
function will return the parent directory's path that is levels up
from the current directory.
Note:
dirname() operates naively on the input string, and is not aware of
the actual filesystem, or path components such as "..".
Caution
dirname() is locale aware, so for it to see the correct directory name
with multibyte character paths, the matching locale must be set using
the setlocale() function.
Parameters~
path
-----
A path.
On Windows, both slash (/) and backslash (\) are used as directory
separator character. In other environments, it is the forward slash
(/).
levels
------
The number of parent directories to go up.
This must be an integer greater than 0.
Return Values~
Returns the path of a parent directory. If there are no slashes in
path, a dot ('.') is returned, indicating the current directory.
Otherwise, the returned string is path with any trailing /component
removed.
Changelog~
Version Description
7.0.0 Added the optional levels parameter.
5.0.0 dirname() is now binary safe
Examples~
Example #1 dirname() example
>
<
For example, if a script called 'database.init.php' which is included
from anywhere on the filesystem wants to include the script
'database.class.php', which lays in the same directory, you can use:
>
<
30 y dot a dot dejong at singular dot of dot alumni dot utwente dot nl ¶2 years ago~
As of PHP 5.3.0, you can use __DIR__ as a replacement for dirname(__FILE__)
7 joe dot naylor at gmail dot com ¶8 years ago~
The dirname function does not usually return a slash on the end, which
might encourage you to create links using code like this: $url =
dirname($_SERVER['PHP_SELF']) . '/somepage.php';
However dirname returns a slash if the path you specify is the root,
so $url in that case would become '//somepage.php'. If you put that
URL as the action on a form, for example, submitting the form will try
to go to http://somepage.php.
I ran into this when I wrote a site on a url with a path,
www.somehost.com/client/somepage.php, where the code above works
great, but then wanted to put it on a subdomain,
client.somehost.com/somepage.php, where things started breaking.
The best solution would be to create a function that generates
absolute URLs and use that throughout the site, but creating a
safe_dirname function (and an htaccess rewrite to fix double-slashes
just in case) fixed the issue for me:
>
<
9 klugg this-is-junk at tlen dot pl ¶11 years ago~
Attention with this. Dirname likes to mess with the slashes. On
Windows, Apache:
>
';
echo 'Dirname($_SERVER[PHP_SELF]: ' . dirname($_SERVER['PHP_SELF']) . ' ';
?>
<
prints out
$_SERVER[PHP_SELF]: /index.php
Dirname($_SERVER[PHP_SELF]: \
--------------------------------------------------------------------------------
*disk_free_space*
+-----------------+~
| disk_free_space |~
+-----------------+~
(PHP 4 >= 4.1.0, PHP 5, PHP 7)
disk_free_space — Returns available space on filesystem or disk partition
Description~
>
float disk_free_space ( string $directory )
<
Given a string containing a directory, this function will return the
number of bytes available on the corresponding filesystem or disk
partition.
Parameters~
directory
---------
A directory of the filesystem or disk partition.
Note:
Given a file name instead of a directory, the behaviour of the
function is unspecified and may differ between operating systems and
PHP versions.
Return Values~
Returns the number of available bytes as a float or FALSE on failure.
Examples~
Example #1 disk_free_space() example
>
<
Notes
Note: This function will not work on remote files as the file to be
examined must be accessible via the server's filesystem.
See Also~
|disk_total_space|() - Returns the total size of a filesystem or disk partition
User Contributed Notes 7 notes
26 wiede at gmx dot net ¶6 years ago~
Transformation is possible WITHOUT using loops:
>
';
echo sprintf('%1.2f' , $bytes / pow($base,$class)) . ' ' . $si_prefix[$class] . ' ';
?>
<
15 Anonymous ¶2 years ago~
$si_prefix = array( 'B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB' );
you are missing the petabyte after terabyte
'B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB'
should look like
'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'
10 sam ¶8 years ago~
Nice, but please be aware of the prefixes.
SI specifies a lower case 'k' as 1'000 prefix.
It doesn't make sense to use an upper case 'K' as binary prefix,
while the decimal Mega (M and following) prefixes in SI are uppercase.
Furthermore, there are REAL binary prefixes since a few years.
Do it the (newest and recommended) "IEC" way:
KB's are calculated decimal; power of 10 (1000 bytes each)
KiB's are calculated binary; power of 2 (1024 bytes each).
The same goes for MB, MiB and so on...
Feel free to read:
http://en.wikipedia.org/wiki/Binary_prefix
10 root at mantoru dot de ¶9 years ago~
Note that disk_free_space() does an open_basedir check.
--------------------------------------------------------------------------------
*disk_total_space*
+------------------+~
| disk_total_space |~
+------------------+~
(PHP 4 >= 4.1.0, PHP 5, PHP 7)
disk_total_space — Returns the total size of a filesystem or disk
partition
Description~
>
float disk_total_space ( string $directory )
<
Given a string containing a directory, this function will return the
total number of bytes on the corresponding filesystem or disk
partition.
Parameters~
directory
---------
A directory of the filesystem or disk partition.
Return Values~
Returns the total number of bytes as a float or FALSE on failure.
Examples~
Example #1 disk_total_space() example
>
<
Notes
Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.
See Also~
|disk_free_space|() - Returns available space on filesystem or disk partition
User Contributed Notes 9 notes
8 Viitala ¶9 years ago~
Beware of empty files!
>
<
8 tularis at php dot net ¶9 years ago~
For a non-looping way to add symbols to a number of bytes:
>
bool feof ( resource $handle )
<
Tests for end-of-file on a file pointer.
Parameters~
handle
------
The file pointer must be valid, and must point to a file successfully
opened by fopen() or fsockopen() (and not yet closed by fclose()).
Return Values~
Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns FALSE.
Notes
Warning
If a connection opened by fsockopen() wasn't closed by the server,
feof() will hang. To workaround this, see below example:
Example #1 Handling timeouts with feof()
>
<
Warning
If the passed file pointer is not valid you may get an infinite loop, because feof() fails to return TRUE.
Example #2 feof() example with an invalid file pointer
>
<
User Contributed Notes 16 notes~
19 ironoxid at libero dot it ¶10 years ago~
I really thought that the feof() was TRUE when the logical file
pointer is a EOF. but no ! we need to read and get an empty record
before the eof() reports TRUE.
So
>
$fp = fopen('test.bin','rb');
while(!feof($fp)) {
$c = fgetc($fp);
// ... do something with $c
echo ftell($fp), ",";
}
echo 'EOF!';
<
prints for two time the last byte position.
If our file length is 5 byte this code prints
0,1,2,3,4,5,5,EOF!
Because of this, you have to do another check to verify if fgetc really reads another byte (to prevent error on "do something with $c" ^_^).
To prevent errors you have to use this code
>
$fp = fopen('test.bin','rb');
while(!feof($fp)) {
$c = fgetc($fp);
if($c === false) break;
// ... do something with $c
}
<
but this is the same of
>
$fp = fopen('test.bin','rb');
while(($c = fgetc($fp))!==false) {
// ... do something with $c
}
<
Consequently feof() is simply useless.
Before write this note I want to submit this as a php bug but one php
developer said that this does not imply a bug in PHP itself
(http://bugs.php.net/bug.php?id=35136&edit=2).
If this is not a bug I think that this need at least to be noticed.
Sorry for my bad english.
Bye ;)
8 sudo dot adam dot carruthers at gmail dot com ¶7 years ago~
When using feof() on a TCP stream, i found the following to work
(after many hours of frustration and anger):
NOTE: I used ";" to denote the end of data transmission. This can be
modified to whatever the server's end of file or in this case, end of
output character is.
>
<
Since strcmp() returns 0 when the two strings are equal, it will
return non zero as long as the cursor is not ";". Using the above
method will add ";" to the string, but the fix for this is simple.
>
<
I hope this helps someone.
--------------------------------------------------------------------------------
*fflush*
+--------+~
| fflush |~
+--------+~
(PHP 4 >= 4.0.1, PHP 5, PHP 7)
fflush — Flushes the output to a file
Description~
>
bool fflush ( resource $handle )
<
This function forces a write of all buffered output to the resource
pointed to by the file handle.
Parameters~
handle
------
The file pointer must be valid, and must point to a file successfully
opened by fopen() or fsockopen() (and not yet closed by fclose()).
Return Values~
Returns TRUE on success or FALSE on failure.
Examples~
Example #1 File write example using fflush()
>
<
See Also~
|clearstatcache|() - Clears file status cache
|fwrite|() - Binary-safe file write
--------------------------------------------------------------------------------
*fgetc*
+-------+~
| fgetc |~
+-------+~
(PHP 4, PHP 5, PHP 7)
fgetc — Gets character from file pointer
Description~
>
string fgetc ( resource $handle )
<
Gets a character from the given file pointer.
Parameters~
handle
------
The file pointer must be valid, and must point to a file successfully
opened by fopen() or fsockopen() (and not yet closed by fclose()).
Return Values~
Returns a string containing a single character read from the file
pointed to by handle. Returns FALSE on EOF.
Warning
This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
Examples~
Example #1 A fgetc() example
>
<
Notes
Note: This function is binary-safe.
See Also~
|fread|() - Binary-safe file read
|fopen|() - Opens file or URL
|popen|() - Opens process file pointer
|fsockopen|() - Open Internet or Unix domain socket connection
|fgets|() - Gets line from file pointer
--------------------------------------------------------------------------------
*fgetcsv*
+---------+~
| fgetcsv |~
+---------+~
(PHP 4, PHP 5, PHP 7)
fgetcsv — Gets line from file pointer and parse for CSV fields
Description~
>
array fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\" ]]]] )
<
Similar to fgets() except that fgetcsv() parses the line it reads for
fields in CSV format and returns an array containing the fields read.
Parameters~
handle
------
A valid file pointer to a file successfully opened by fopen(),
popen(), or fsockopen().
length
------
Must be greater than the longest line (in characters) to be found in
the CSV file (allowing for trailing line-end characters). Otherwise
the line is split in chunks of length characters, unless the split
would occur inside an enclosure.
Omitting this parameter (or setting it to 0 in PHP 5.1.0 and later)
the maximum line length is not limited, which is slightly slower.
delimiter
---------
The optional delimiter parameter sets the field delimiter (one
character only).
enclosure
---------
The optional enclosure parameter sets the field enclosure character
(one character only).
escape
------
The optional escape parameter sets the escape character (one character
only).
Return Values~
Returns an indexed array containing the fields read.
Note:
A blank line in a CSV file will be returned as an array comprising a
single null field, and will not be treated as an error.
Note: If PHP is not properly recognizing the line endings when reading
files either on or created by a Macintosh computer, enabling the
auto_detect_line_endings run-time configuration option may help
resolve the problem.
fgetcsv() returns NULL if an invalid handle is supplied or FALSE on
other errors, including end of file.
Changelog~
Version Description
5.3.0 The escape parameter was added
5.1.0 The length is now optional. Default is 0, meaning no length limit.
4.3.5 fgetcsv() is now binary safe
Examples~
Example #1 Read and print the entire contents of a CSV file
>
$num fields in line $row:
\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . " \n";
}
}
fclose($handle);
}
?>
<
Notes
Note:
Locale setting is taken into account by this function. If LANG is e.g.
en_US.UTF-8, files in one-byte encoding are read wrong by this
function.
See Also~
|str_getcsv|() - Parse a CSV string into an array
|explode|() - Split a string by string
|file|() - Reads entire file into an array
|pack|() - Pack data into binary string
|fputcsv|() - Format line as CSV and write to file pointer
User Contributed Notes 58 notes
46 james dot ellis at gmail dot com ¶8 years ago~
If you need to set auto_detect_line_endings to deal with Mac line
endings, it may seem obvious but remember it should be set before
fopen, not after:
This will work:
>
<
This won't, you will still get concatenated fields at the new line position:
>
<
25 myrddin at myrddin dot myrddin ¶10 years ago~
Here is a OOP based importer similar to the one posted earlier.
However, this is slightly more flexible in that you can import huge
files without running out of memory, you just have to use a limit on
the get() method
Sample usage for small files:-
-------------------------------------
get();
print_r($data);
?>
Sample usag