Php substitution of variables in a string. Using templates in PHP

(PHP 4, PHP 5, PHP 7)

str_replace- Replaces all occurrences of the search string with the replacement string

Description

This function returns a string or array with all occurrences of search in subject replaced by replace .

If you don't need complex find/replace rules (such as regular expressions), this function is preferable. preg_replace().

Parameter List

If search and replace are arrays, then str_replace() uses each value from the corresponding array to search and replace in subject . If there are fewer elements in the replace array than in search , the empty string will be used as the replacement string for the remaining values. If search is an array and replace is a string, then that replacement string will be used for each element of the search array. The reverse case doesn't make sense.

If search or replace are arrays, their elements will be processed from first to last.

The value you are looking for, also known as needle(needle). You can use an array for multiple search values.

Replace

The replacement value will be used to replace the searched search values. You can use an array for multiple values.

Subject

The string or array to be searched and replaced, also known as haystack(haystack).

If subject is an array, then the search and replace will be performed on each element of subject , and the result of the function will also be an array.

If passed, it will be set to the number of replacements made.

Return Values

This function returns a string or array with the values ​​replaced.

Examples

Example #1 Usage examples str_replace()

// assigns
$bodytag = str_replace("%body%" , "black" , " " );

// assign: Hll Wrld f PHP
$vowels = array("a" , "e" , "i" , "o" , "u" , "A" , "E" , "I" , "O" , "U" );
$onlyconsonants = str_replace ($vowels , "" , "Hello World of PHP" );

// assigns: 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 );

// assign: 2
$str = str_replace ("ll" , "" , "good golly miss molly!" , $count );
echo $count ;
?>

Example #2 Examples of potential tricks with str_replace()

// Replacement Order
$str = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order = array("\r\n" , "\n" , "\r" );
$replace = "
" ;

// Handles \r\n first to avoid replacing them again.
echo $newstr = str_replace ($order , $replace , $str );

// Outputs F, because A is replaced by B, then B by C, and so on...
// As a result, E will be replaced by F, since the replacement occurs from left to right.
$search = array("A" , "B" , "C" , "D" , "E" );
$replace = array("B" , "C" , "D" , "E" , "F" );
$subject = "A" ;
echo str_replace ($search , $replace , $subject );

// Outputs: apple, nut, nut (for the reason above)
$letters = array("I" , "o" );
$fruit = array("apple" , "nut" );
$text = "I'm about" ;
$output = str_replace ($letters , $fruit , $text );
echo $output ;
?>

Notes

Comment: This function is safe to handle data in binary form.

Warning

Note on replacement order

Because str_replace() replaces from left to right, then when using multiple replacements, it can replace a previously inserted value with another. See also examples on this page.

Comment:

This function is case sensitive. Use str_place() for a case-insensitive replacement.

Comment: In PHP 7.0.0 on 64-bit platforms there is no reachable string length limit, on 32-bit systems and earlier PHP versions, rows cannot be larger than 2 GB (2147483647 bytes).

Syntax

A string can be defined with four different ways:

  • single quotes
  • double quotes
  • nowdoc syntax (since PHP 5.3.0)

Single quotes

The simplest way to define a string is to enclose it in single quotes (symbol " ).

To use a single quote within a string, escape it with a backslash ( \ ). If you need to write the backslash itself, duplicate it ( \\ ). All other backslashes will be interpreted as regular characters, which means that if you try to use other escape sequences such as \r or \n, they will be output as is instead of any special behavior.

echo "this is a simple string";

echo "Also, you can insert into lines
newline character like this,
this is normal"
;

// Outputs: One day Arnold said: "I"ll be back"
echo "One day Arnold said, "I\"ll be back"";

echo "Did you delete C:\\*.*?";

// Outputs: Did you delete C:\*.*?
echo "Did you delete C:\*.*?" ;

// Output: This will not be expanded: \n new line
echo "This will not expand: \n newline";

// Prints: $expand variables are also not expanded by $either
echo "Variables $expand also $either are not expanded";
?>

Double quotes

If the string is enclosed in double quotes ("), PHP recognizes the following special character escape sequences:

Escape sequences
Subsequence Meaning
\n newline (LF or 0x0A (10) in ASCII)
\r carriage return (CR or 0x0D (13) in ASCII)
\t horizontal tab (HT or 0x09 (9) in ASCII)
\v vertical tab (VT or 0x0B (11) in ASCII) (since PHP 5.2.5)
\e escape character (ESC or 0x1B(27) in ASCII) (since PHP 5.4.4)
\f page feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)
\\ backslash
\$ dollar sign
\" double quote
\{1,3} sequence of characters matching a regular expression of a character in octal that silently overflows to fit in a byte (i.e. "\400" === "\000")
\x(1,2) a sequence of characters that matches a character regular expression in hexadecimal
\u(+) a character sequence matching a Unicode character regular expression that maps to a string in UTF-8 representation (added in PHP 7.0.0)

As with a string enclosed in single quotes, escaping any character will also print the escape character itself. Prior to PHP 5.1.1, the backslash in \($var) not printed.

Heredoc

The third way to define strings is using the heredoc syntax: <<< . After this statement, you must specify an identifier, then a newline. After that comes the line itself, and then the same identifier that closes the insert.

Line should start with a closing identifier, i.e. it should be in the first column of the row. In addition, the identifier must follow the same naming conventions as all other PHP tags: contain only alphanumeric characters and underscores, and must not start with a number (underscores are allowed).

Attention

It is very important to note that the string with the closing identifier must not contain other characters, except for the semicolon ( ; ). This means that the ID must not be indented and that there can't be any spaces or tabs before or after the semicolon. It is also important to understand that the first character before the closing identifier must be a newline character, as defined by your operating system. For example, on UNIX systems, including macOS, this is \n. The closing identifier must also be immediately followed by a newline.

If this rule is violated and the closing identifier is not "clean", it is considered that there is no closing identifier and PHP will continue searching for it. If, in this case, the correct closing identifier is never found, then this will cause a parsing error with a line number at the end of the script.

Beispiel #1 Incorrect syntax example

class foo(
public $bar =<<bar
EOT;
// padding before the closing identifier is not allowed
}
?>

Beispiel #2 Correct syntax example

class foo(
public $bar =<<bar
EOT;
}
?>

Heredoc cannot be used to initialize class fields. As of PHP 5.3, this restriction only applies to heredocs that contain variables within them.

Heredoc text behaves the same as a double-quoted string without having them. This means you don't need to escape quotes in the heredoc, but you can still use the above escape sequences. Variables are handled, but you need to be as careful when using complex variables inside a heredoc as you would when working with strings.

Beispiel #3 heredoc string definition example

$str =<<Line example,
spanning multiple lines
using the heredoc syntax.
EOD;

Class foo
{
var $foo ;
var $bar ;

Function __construct()
{
$this -> foo = "foo" ;
$this ->
}
}

$foo = newfoo();
$name = "Name" ;

echo<<My name is " $name ". I type $foo -> foo .
Now I'm taking out
( $foo -> bar [ 1 ]) .
This should output an uppercase "A": \x41
EOT;
?>

My name is "Name". I am typing Foo. Now, I am outputting Bar2. This should output an uppercase "A": A

It is also possible to use heredoc syntax to pass data through function arguments:

Since version 5.3.0, it has become possible to initialize static variables and class properties/constants using the heredoc syntax:

Beispiel #5 Using heredoc to initialize static variables

// Static variables
functionfoo()
{
static $bar =<<There's nothing here...
label;
}

// Class constants/properties
class foo
{
const BAR =<<An example of using a constant
FOOBAR;

Public $base =<<Field usage example
FOOBAR;
}
?>

As of PHP 5.3.0, it is also possible to surround the Heredoc identifier with double quotes:

Nowdoc

Nowdoc is the same for single-quoted strings as heredoc is for double-quoted strings. Nowdoc is similar to heredoc, but inside it no substitutions are made. This construct is ideal for embedding PHP code or other large blocks of text without having to escape it. In this it is a bit similar to the SGML construct. by declaring a block of text not intended to be processed.

Nowdoc is indicated by the same sequence <<< , which is used in the heredoc, but the identifier that follows it is enclosed in single quotes, for example, <<<"EOT" . All conditions that apply to heredoc identifiers also apply to nowdoc, especially those that apply to the closing identifier.

Beispiel #7 nowdoc example

echo<<<"EOD"
text example,
spanning multiple lines
using nowdoc syntax. Backslashes are always treated literally,
for example, \\ and \".
EOD;

The result of running this example:

An example of text spanning multiple lines using the nowdoc syntax. Backslashes are always treated literally, like \\ and \".

Example #8 Nowdoc string quoting example with variables

/* More complex example with variables. */
class foo
{
public $foo ;
public $bar ;

Function __construct()
{
$this -> foo = "foo" ;
$this -> bar = array("Bar1" , "Bar2" , "Bar3" );
}
}

$foo = newfoo();
$name = "Name" ;

echo<<<"EOT"
My name is "$name". I am typing $foo->foo.
Now I'm typing ($foo->bar).
This should not output a capital "A": \x41
EOT;
?>

The result of running this example:

My name is "$name". I am typing $foo->foo. Now I'm typing ($foo->bar). This should not output a capital "A": \x41

Example #9 Static data example

class foo(
public $bar =<<<"EOT"
bar
EOT;
}
?>

Comment:

nowdoc support was added in PHP 5.3.0.

Processing Variables

If a string is specified in double quotes or with a heredoc, the variables inside it are processed.

There are two types of syntax: simple and complex. The simple syntax is easier and more convenient. It makes it possible to process a variable, an array value ( array) or object properties ( object) with minimal effort.

Complex syntax can be identified by the curly braces surrounding the expression.

Simple Syntax

If the interpreter encounters a dollar sign ( $ ), it captures as many characters as possible to form the correct variable name. If you want to specify the end of a name, enclose the variable name in curly braces.

$juice = "apple" ;

echo "He drank some $juice juice." . PHP_EOL ;

// Incorrect. "s" is a valid character for a variable name, but the variable name is $juice.
echo "He drank some juice made of $juices ." ;

// Correct. The end of the variable name is strictly specified using brackets:
echo "He drank some juice made of $( juice ) s." ;
?>

The result of running this example:

He drank some apple juice. He drank some juice made of. He drank some juice made of apples.

An element of an array ( array) or object property ( object). In array indices, the closing square bracket ( ] ) marks the end of the index definition. The same rules apply to object properties as to simple variables.

Example #10 Simple syntax example

define("KOOLAID" , "koolaid1" );
$juices = array("apple" , "orange" , "koolaid1" => "purple" );

echo "He drank some $juices [ 0 ] juice." . PHP_EOL ;
echo "He drank some $juices [ 1 ] juice." . PHP_EOL ;
echo "He drank some $juices [ koolaid1 ] juice." . PHP_EOL ;

class people(
public $john = "John Smith" ;
public $jane = "Jane Smith" ;
public $robert = "Robert Paulsen" ;

Public $smith = "Smith" ;
}

$people = new people();

echo " $people -> john drank some $juices [ 0 ] juice." . PHP_EOL ;
echo " $people -> john then said hello to $people -> jane ." . PHP_EOL ;
echo " $people -> john "s wife greeted $people -> robert." . PHP_EOL ;
echo " $people -> robert greeted the two $people -> smiths ." ; // Won't work
?>

The result of running this example:

He drank some apple juice. He drank some orange juice. He drank some purple juice. John Smith drank some apple juice. John Smith then said hello to Jane Smith. John Smith's wife greeted Robert Paulsen. Robert Paulsen greeted the two.

PHP 7.1.0 added support negative numeric indexes.

Example #11 Negative numeric indices

$string = "string" ;
echo "The character at index -2 is$string [- 2 ] ." , PHP_EOL ;
$string [- 3 ] = "o" ;
echo "Changing the character at position -3 to 'o' produces the following line:$string ." , PHP_EOL ;
?>

The result of running this example:

The character with index -2 is n. Changing the character at position -3 to "o" produces the following string: strong

For anything more complex, use complex syntax.

Complex (curly) syntax

It is called complex not because it is difficult to understand, but because it allows the use of complex expressions.

Any scalar variable, array element, or object property mapped to a string can be represented in a string with this syntax. Just write the expression just like you would outside the string and then enclose it in { And } . Insofar as { cannot be escaped, this syntax will only be recognized when $ follows directly after { . Use {\$ to print {$ . A few illustrative examples:

// Show all errors
error_reporting(E_ALL);

$great = "great" ;

// Doesn't work, outputs: This (great)
echo "This is ( $great )" ;

// Works, outputs: This is great
echo "This is ($great)" ;

// Working
echo "This square is wide( $square -> width ) 00 centimeters." ;

// Works, quoted keys only work with curly bracket syntax
echo "This works: ( $arr [ "key" ]) " ;

// Working
echo "This works: ( $arr [ 4 ][ 3 ]) " ;

// This is wrong for the same reason that $foo is outside
// lines. In other words, it will still work
// but since PHP looks for the foo constant first, this will call
// E_NOTICE level error (undefined constant).
echo "It is not right:( $arr [ foo ][ 3 ]) " ;

// Working. When using multidimensional arrays inside
// strings always use curly braces
echo "This works: ( $arr [ "foo" ][ 3 ]) " ;

// Working.
echo "This works: " . $arr [ "foo" ][ 3 ];

echo "This also works:( $obj -> values ​​[ 3 ]-> name ) " ;

echo "This is the value of the variable named$name : ($( $name )) " ;

echo "This is the value of the variable by name, which is returned by the getName() function:($( getName ())) ";

echo "This is the value of the variable by name returned by \$object->getName():($( $object -> getName ())) " ;

// Doesn't work, outputs: This is what getName() returns: (getName())
echo "This is what getName() returns: (getName())";
?>

It is also possible to access object properties within strings using this syntax.

class foo(
var $bar = "I am bar." ;
}

$foo = newfoo();
$bar = "bar" ;
$baz = array("foo" , "bar" , "baz" , "quux" );
echo " ( $foo -> $bar ) \n" ;
echo " ( $foo ->( $baz [ 1 ])) \n" ;
?>

The result of running this example:

I am bar. I am bar.

Comment:

Functions, method calls, static class variables, and class constants work internally {$} , starting with PHP 5. However, the specified value will be treated as a variable name in the same context as the string in which it is defined. Using single curly braces ( {} ) will not work for accessing the values ​​of functions, methods, class constants, or static class variables.

// Show all errors
error_reporting(E_ALL);

class beers(
const softdrink = "rootbeer" ;
public static $ale = "ipa" ;
}

$rootbeer = "A & W" ;
$ipa = "Alexander Keith\"s" ;

// This works, outputs: I would like A & W
echo "I'd like ($( beers :: softdrink )) \n" ;

// This also works, outputs: I would like Alexander Keith"s
echo "I'd like ($( beers :: $ale )) \n" ;
?>

Accessing a character in a string and changing it

Characters in strings can be used and modified by specifying their offset from the beginning of the string, starting at zero, in square brackets after the string, for example, $str . Think of a string for this purpose as an array of characters. If you need to get or replace more than 1 character, you can use the functions substr() And substr_replace().

Comment: since PHP 7.1.0, negative offset values ​​are supported. They set the offset from the end of the string. Previously, negative offsets caused a level error E_NOTICE when read (returning an empty string) or E_WARNING on write (leaving the string unchanged).

Comment: A character in a string can also be accessed using curly braces, such as $str(42) .

Attention

Attempting to write to an offset outside the string will pad the string with spaces up to that offset. Non-integer types will be converted to integers. Wrong offset type will cause level error E_WARNING. Only the first character of the assigned string is used. As of PHP 7.1.0, assigning an empty string will cause a fatal error. Previously, in this case, a null byte (NULL) was assigned.

Attention

Strings in PHP are internally arrays of bytes. As a result, accessing or modifying a string by offset is not multibyte safe, and should only be done with strings in single-byte encodings such as ISO-8859-1.

Comment: Since PHP 7.1.0, the use of an empty index causes a fatal error, previously in such a case the string was converted to an array without warning.

Example #12 Several example strings

// Get the first character of the string
$str = "This is a test." ;
$first = $str [ 0 ];

// Get the third character of the string
$third = $str [ 2 ];

// Get the last character of the string
$str = "This is still a test." ;
$last = $str [ strlen($str )- 1 ];

// Change the last character of the string
$str = "Look at the sea" ;
$str [ strlen ($str )- 1 ] = "e" ;

?>

As of PHP 5.4, the offset in a string must be either an integer or a string containing numbers, otherwise a warning will be issued. Previously, an offset given by a string like "foo", without warning was converted to 0 .

Example #13 Differences between PHP 5.3 and PHP 5.4

$str = "abc" ;

Var_dump($str["1"]);
var_dump (isset($str [ "1" ]));

Var_dump($str[ "1.0" ]);
var_dump (isset($str [ "1.0" ]));

Var_dump($str["x"]);
var_dump (isset($str [ "x" ]));

Var_dump($str[ "1x" ]);
var_dump (isset($str [ "1x" ]));
?>

The result of running this example in PHP 5.3 is:

string(1) "b" bool(true) string(1) "b" bool(true) string(1) "a" bool(true) string(1) "b" bool(true)

The result of running this example in PHP 5.4 is:

string(1) "b" bool(true) Warning: Illegal string offset "1.0" in /tmp/t.php on line 7 string(1) "b" bool(false) Warning: Illegal string offset "x" in / tmp/t.php on line 9 string(1) "a" bool(false) string(1) "b" bool(false)

Comment:

Attempting to access variables of other types (excluding arrays or objects that implement certain interfaces) with or {} silently return NULL.

Comment:

PHP 5.5 added support for accessing characters in string literals using the syntax or {} .

There are many useful functions for modifying strings.

The main functions are described in the string functions section, and for advanced search and replace, Perl-compatible regular expression functions.

Convert to string

The value can be converted to a string using a cast (string), or functions strval(). In expressions where a string is needed, the conversion occurs automatically. This happens when you use functions echo or print, or when the value of a variable is compared to a string. Reading the Types and Type Manipulation sections of the manual will make the following clearer. see also settype().

Arrays are always converted to string "array", so you can't display the contents of the array ( array) using echo or print to see what it contains. To view an individual element, use something like echo $arr["foo"]. See below for tips on how to display/view all content.

To convert a type variable "Object" per type string the magic method __toString is used.

Meaning NULL always converted to the empty string.

As you can see above, direct stringization of arrays, objects, or resources does not provide any useful information about the values ​​themselves, other than their types. A more appropriate way to output values ​​for debugging is to use functions print_r() And var_dump().

Most values ​​in PHP can be converted to a string for permanent storage. This method is called serialization and can be done with the function serialize().

Converting strings to numbers

If the string is recognized as a numeric value, the resulting value and type is determined as follows.

If the string does not contain any of the characters ".", "e", or "E", and the value of the number fits within the range of integers (defined PHP_INT_MAX), the string will be recognized as an integer ( integer). In all other cases, it is considered a floating point number ( float).

The value is determined by the initial part of the string. If the string starts with a valid numeric value, that value will be used. Otherwise, the value will be 0 (zero). A valid numeric value is one or more digits (which may contain a decimal point), optionally preceded by a sign, followed by an optional exponent. The exponent is "e" or "E" followed by one or more digits.

$foo = 1 + "10.5" ; // $foo is a float (11.5)
$foo = 1 + "-1.3e3" ; // $foo is a float (-1299)
$foo = 1 + "bob-1.3e3" ; // $foo is an integer (1)
$foo = 1 + "bob3" ; // $foo is an integer (1)
$foo = 1 + "10 Small Pigs" ; // $foo is an integer (11)
$foo = 4 + "10.2 Little Piggies" ; // $foo is a float (14.2)
$foo = "10.0 pigs" + 1 ; // $foo is a float (11)
$foo = "10.0 pigs" + 1.0 ; // $foo is a float (11)
?>

See the strtod(3) section of the Unix documentation for more information on this conversion.

If you want to test any of the examples in this section, copy and paste it and the following line to see what happens:

echo "\$foo== $foo ; type: " . gettype ($foo ) . "
\n" ;
?>

Don't expect to get the character code by converting it to an integer (as is done, for example, in C). To convert characters to their ASCII codes and vice versa, use the functions ord() And chr().

String Type Implementation Details

7 years ago

The documentation does not mention, but a closing semicolon at the end of the heredoc is actually interpreted as a real semicolon, and as such, sometimes leads to syntax errors.

$foo =<<abcd
END;
?>

This does not:

foo(<<abcd
END;
);
// syntax error, unexpected ";"
?>

Without semicolon, it works fine:

foo(<<abcd
END
);
?>

3 years ago

You can use string like array of char (like C)

$a = "String array test";

var_dump($a);
// Return string(17) "String array test"

var_dump($a);
// Return string(1) "S"

// -- With array cast --
var_dump((array)$a);
// Return array(1) ( => string(17) "String array test")

var_dump((array)$a);
// Return string(17) "S"

Norihiori

15 years ago

You can use the complex syntax to put the value of both object properties AND object methods inside a string. For example...
class Test(
public $one = 1 ;
public function two()(
return 2 ;
}
}
$test = new Test();
echo "foo ( $test -> one ) bar ( $test -> two ()) " ;
?>
Will output "foo 1 bar 2".

However, you cannot do this for all values ​​in your namespace. Class constants and static properties/methods will not work because the complex syntax looks for the "$".
class Test(
const ONE = 1 ;
}
echo "foo (Test::ONE) bar" ;
?>
This will output "foo (Test::one) bar". Constants and static properties require you to break up the string.

3 years ago

Beware that consistent with "String conversion to numbers":

If ("123abc" == 123 ) echo "(intstr == int) incorrectly tests as true.";

// Because one side is a number, the string is incorrectly converted from intstr to int, which then matches the test number.

// True for all conditionals such as if and switch statements (probably also while loops)!

// This could be a huge security risk when testing/using/saving user input, while expecting and testing for only an integer.

// It seems the only fix is ​​for 123 to be a string as "123" so no conversion happens.

?>

6 years ago

Leading zeroes in strings are (least-surprise) not treated as octal.
Consider:
$x = "0123" + 0;
$y = 0123 + 0;
echo "x is $x, y is $y"; //prints "x is 123, y is 83"
in other words:
* leading zeros in numeric literals in the source-code are interpreted as "octal", c.f. strtol().
* leading zeros in strings (eg user-submitted data), when cast (implicitly or explicitly) to integer are ignored, and considered as decimal, c.f. strtod().

10 years ago

Here is an easy hack to allow double-quoted strings and heredocs to contain arbitrary expressions in curly braces syntax, including constants and other function calls:

// Hack declaration
function_expr ($v ) ( return $v ; )
$_expr = "_expr" ;

// Our playground
define("qwe" , "asd");
define("zxc", 5 );

$a= 3 ;
$b= 4 ;

function c($a, $b) (return$a+ $b; }

// Usage
echo"pre{ $_expr(1 + 2 )} post\n"; // outputs "pre 3 post"
echo"pre{ $_expr(qwe)} post\n"; // outputs "pre asd post"
echo"pre{ $_expr(c($a, $b)+ zxc* 2 )} post\n"; // outputs "pre 17 post"

// General syntax is ($_expr(...))
?>

2 years ago

I though that it would be helpful to add this comment so that the information at least appears on the right page on the PHP site.

Note that if you intend to use a double-quoted string with an associative key, you may run into the T_ENCAPSED_AND_WHITESPACE error. Some regard this as one of the less obvious error messages.

An expression such as:

$fruit=array(
"a"=> "apple",
"b"=> banana,
//etc
);

print "This is a$fruit[ "a"]"; // T_ENCAPSED_AND_WHITESPACE
?>

will definitely fall to pieces.

You can resolve it as follows:

print"This is a$fruit[ a] " ; // unquote the key
print"This is a${ fruits[ "a"]} " ; // Complex Syntax
print"This is a{ $fruit[ "a"]} " ; // Complex Syntax variation
?>

I have a personal preference for the last variation as it is more natural and closer to what the expression would be like outside the string.

It's not clear (to me, at least) why PHP misinterprets the single quote inside the expression but I imagine that it has something to do with the fact quotes are not part of the value string - once the string is already being parsed the quotes just get in the way … ?

2 years ago

Both should work:(

classtesting{
public static
$var= "static";
public const VAR =
"const";

public function sayHelloStatic() {
echo
hello:{ $this:: $var} " ;
}

public function sayHelloConst() {
echo
hello:{ $this::VAR)" ; //Parse error: syntax error, unexpected ")", expecting "["
}
}

$obj= newtesting();
$obj-> sayHelloStatic();
$obj-> sayHelloConst();

3 years ago

Something I experienced which no doubt will help someone. . .
In my editor, this will syntax highlight HTML and the $comment:

$html =<<<"EOD"
$comment
EOD;

Using this shows all the same colors:

$html =<<$comment
EOD;

making it a lot easier to work with

11 years ago

To save Your mind don "t read previous comments about dates ;)

When both strings can be converted to the numerics (in ("$a" > "$b") test) then resulted numerics are used, else FULL strings are compared char-by-char:

var_dump("1.22" > "01.23" ); // bool(false)
var_dump("1.22.00" > "01.23.00" ); // bool(true)
var_dump("1-22-00" > "01-23-00" ); // bool(true)
var_dump((float)"1.22.00" > (float)"01.23.00" ); // bool(false)
?>

mixed preg_replace(mixed pattern, mixed replacement, mixed subject [, int limit])

Searches subject for matches of pattern and replaces them with replacement . If the limit parameter is specified, the limit occurrences of the template will be replaced; if limit is omitted or equals -1, all occurrences of the pattern will be replaced.

Replacement can contain references of the form \\ n or (as of PHP 4.0.4) $n , the latter being preferred. Each such reference will be replaced with a substring corresponding to the nth parenthesized subpattern. n can take values ​​from 0 to 99, with the reference \\0 (or $0) corresponding to the occurrence of the entire pattern. Subpatterns are numbered from left to right, starting from one .

When using wildcard substitution using subpattern references, there may be a situation where a digit immediately follows the mask. In this case, the \\n notation results in an error: a reference to the first subpattern followed by a 1 will be written as \\11 , which will be interpreted as a reference to the eleventh subpattern. This misunderstanding can be eliminated by using the \$(1)1 construct, which points to an isolated reference to the first subpattern, followed by the digit 1 .

The output of this example will be:

April1,2003

If a pattern match is found during the execution of the function, the modified value of subject will be returned, otherwise the original text of subject will be returned.

The first three parameters of the function preg_replace() can be one-dimensional arrays. If the array uses keys, then when processing the array, they will be taken in the order in which they are located in the array. Specifying keys in the array for pattern and replacement is optional. If you still decide to use indexes, use the function to match the patterns and strings involved in the replacement. ksort() for each of the arrays.


Example 2: Using Arrays with Numeric Indexes as Function Arguments preg_replace()

$string = "The quick brown fox jumped over the lazy dog.";$patterns [ 0 ] = "/quick/" ;
$patterns [ 1 ] = "/brown/" ;
$patterns [ 2 ] = "/fox/" ;$replacements [ 2 ] = "bear" ;
$replacements [ 1 ] = "black" ;
$replacements [ 0 ] = "slow" ;preg_replace ($patterns , $replacements , $string );
?>

Result:

Result:

The slow black bear jumped over the lazy dog.

If the subject parameter is an array, a pattern search and replace is performed for each of its elements. The returned result will also be an array.

In case the parameters pattern and replacement are arrays, preg_replace() extracts a pair of elements from both arrays in turn and uses them for the search and replace operation. If the replacement array contains more elements than pattern , empty strings will be taken instead of the missing elements for replacement. If pattern is an array and replacement is a string, each element of pattern will be searched and replaced by pattern (the pattern will be all array elements in turn, while the replacement string remains fixed). The option when pattern is a string and replacement is an array does not make sense.

The /e modifier changes the behavior of the function preg_replace() in such a way that the replacement parameter, after performing the necessary substitutions, is interpreted as PHP code and only then used for replacement. When using this modifier, be careful: the replacement parameter must contain valid PHP code, otherwise in the line containing the function call preg_replace(), a syntax error will occur.


Example 3: Replace with multiple patterns

$patterns = array ( "/(19|20)(\d(2))-(\d(1,2))-(\d(1,2))/",
"/^\s*((\w+))\s*=/" );
$replace = array("\\3/\\4/\\1\\2" , "$\\1 =" );
echo preg_replace ($patterns , $replace , "(startDate) = 1999-5-27" );
?>

This example will output:

Converts all HTML tags to uppercase


Example 5. HTML to text converter

// $document output must contain an HTML document.
// Need to remove all HTML tags, javascript sections,
// whitespace characters. It is also necessary to replace some
// HTML entities to their equivalent.
$search = array( ""]*?>.*?"si", // Cut out javaScript
""<[\/\!]*?[^<>]*?>"si" , // Strips HTML tags
""([\r\n])[\s]+"" , // Strips whitespace characters
""&(quot|#34);"i" , // Replaces HTML entities
""&(amp|#38);"i" ,
""&(lt|#60);"i" ,
""&(gt|#62);"i" ,
""&(nbsp|#160);"i" ,
""&(iexcl|#161);"i" ,
""&(cent|#162);"i" ,
""&(pound|#163);"i" ,
""&(copy|#169);"i" ,
""(\d+);"e"); // interpret as php code$replace = array("" ,
"" ,
"\\1" ,
"\"" ,
"&" ,
"<" ,
">" ,
" " ,
chr(161),
chr(162),
chr(163),
chr(169 ),
"chr(\\1)" );$text = preg_replace ($search , $replace , $document );
?>



Tables:

C_id | company | location
1 | OOO Search | Kudykino field 15/3
2 | CJSC Elita | Slunysvalinsk 133/7
3 | OJSC Pyshpyshch | Soldatodachestroyskoe 404

Repair type (repair_types)
r_id | repair_types |
1 | Hammer + nails
2 | Beauty guidance
3 | Overhaul

List of orders (list)
l_id | Who | What need | time | operator comment
1 | 1 | 2 | %timestamp% | %operator_text%
2 | 2 | 1 | | %text%
3 | 3 | 2 | | %text%

Table #1 contains a list of clients.
Table #2 contains a list of services.
Table No. 3 contains a list of current orders for operational teams. This table is regularly updated and a web form is used to fill it. Since quite a lot of orders come in, records are entered in the table in the form of a client ID and a service.

Actually, the problem is that the third table should be displayed in the "order selection" web form, and instead of ID, you need to substitute the corresponding fields from other columns.

The code:
$query = "SELECT * FROM list";
$result = mysql_query($query);
while($row=mysql_fetch_array($result. // get results from each row
( echo "";// display data
}




CREATE TABLE "table_name" ("id" int(255) NOT NULL AUTO_INCREMENT, "list" text (80) NOT NULL, PRIMARY KEY("id".

INSERT INTO "table_name" ("list") VALUES ("bla-bla")



best answer $query =
"
select companies.Company, repair_types.Repair_types, list.comment_l
from list
inner join companies
on list.Who = companies.c_id
inner join repair_types
on list."What need" = repair_types.r_id
";

Recently, discussions of the PHP language on Habré have been reduced more to the ability to design complex systems, which cannot but rejoice. However, after reviewing a dozen of the most recognized web frameworks (Zend Framework, Adept, CakePHP, CodeIgniter, LIMB, Symfony, MZZ and others), I was genuinely surprised to find some significant shortcomings in terms of elementary optimization.

In order for this topic to be more technically oriented, the results are presented in a more strict form, which may complicate the perception somewhat.

So, let's go ... The task is extremely simple: to conduct experiments on the speed of forming strings from substrings in single and double quotes. In principle, this question will be relevant for a long time due to the peculiarities of string processing in PHP.

There are many articles on basic script optimization both in Russian and in other languages. Little is said about strings, but the fact of "parsing" strings in double quotes for variables and control characters is noted (however, as in the official documentation). Based on this, it is logical to assume that the use of double-quoted strings at work will be somewhat slower than the same operations with single-quoted substrings.

In addition to substituting variables into strings and concatenating variables with substrings, PHP implements at least one more way to form strings: working with the sprintf function. It is logical to assume that this method will be significantly inferior to the "standard" ones due to an extra function call and string parsing inside.

The only addition, before I present you the test script code: there are 2 possible options for working with double-quoted strings: taking into account the simple and "advanced" coding style. The fact that the variables are at the very beginning of the lines is probably not worth paying attention to - they are only examples:
$string = "$_SERVER["HTTP_HOST"] is not the administration of the Ulyanovsk region. We love the Russian language and don't like those who speak it..."
And
$string = "($_SERVER["HTTP_HOST"]) is not the administration of the Ulyanovsk region. We love the Russian language and don't like those who speak it..."

Test number one.
Well, it seems that all the reservations have been made - it's time to show the results of the work. The tester's source code can be found at .

The screenshots show that my hypothesis was not confirmed. The assumption about working with strings through sprintf turned out to be the only correct one. The fastest were the functions that work with double quotes.

After a short reflection on the situation, the explanation came by itself: the whole point is that the reference string into which the substitutions were made is too short: the parser passing through such a string is a trifling matter. However, even here it is clear that native substitution of a variable into a string gives an advantage over the "advanced style".
This is also the weakness of the concatenation approach: the volume of inserted data exceeds the volume of substrings. Where overheads come from can be read in the already mentioned habratopic.

However, even these thoughts needed to be confirmed. For this, a second test was needed with changes to the possible reasons mentioned for such unpredictable (for me) behavior. Apparently, a lot of things have been tweaked in the fifth version (I confess that in the fifth version of php I conducted only 1 test: to bypass array elements).

Test number two.
The second hypothesis is that lengthening the reference string will eventually increase the percentage of tester functions associated with the formation of strings in double quotes, relative to the results of test number 1. The same situation, theoretically, should be observed with respect to the operation of the sprintf function. This is due, first of all, to the need for string parsing and the increase in time spent on it. In the situation with the concatenation of substrings in single quotes, I think that the result will be approximately the same as in the first test, which will give a slight decrease in the proportion of the execution time of the quotes_3() function by the time of the entire script (but not a performance increase).

Conclusions, in fact, only positive and confirming the hypothesis. When the reference string is slightly increased, there is a large load, which leads to a drop in performance of the double quotes and sprintf functions.

The assumption about strings in single quotes also turned out to be correct: instead of 36.75% of the time in the first test, in the second, the quotes_3() function took 33.76% of the script execution time

practical value.
In simple terms, abstracting from the data, we can conclude that the longer the string in which it is necessary to perform the substitution, the more likely it is that the concatenation operation will be completed faster than searching for a variable in double quotes. Volunteers can try to choose the necessary insertion parameters (number of variables, length of the reference string, lengths of strings in the variables) such that they satisfy the equality of execution times.

That, in fact, is all. It remains only to add that there are no trifles in programming (this is for those who like to say “saving on matches” (c) Adelf). Knowing such subtleties and taking them into account, you can write code that will be optimized at all its levels;)

PS:
Tests performed using Zend Studio For Eclipse 6.0.0 (Debugger + Profiler included).
PHP Version 5.2.5
Debian Linux OS

PPS:
I would be glad if someone will post their results of these tests. I think this will allow a more objective assessment of the need to use one or another method of substitution into strings. I would also be grateful for healthy criticism of the style of presentation and design.