Professional Documents
Culture Documents
http://php.net/manual/es/language.types.string.php
Downloads
Documentation
Get Involved
Help
Search
PHPKonf: Istanbul PHP Conference 2017
Getting Started
Introduction
A simple tutorial
Language Reference
Basic syntax
Types
Variables
Constants
Expressions
Operators
Control Structures
Functions
Classes and Objects
Namespaces
Errors
Exceptions
Generators
References Explained
Predefined Variables
Predefined Exceptions
Predefined Interfaces and Classes
Context options and parameters
Supported Protocols and Wrappers
Security
Introduction
General considerations
Installed as CGI binary
Installed as an Apache module
Session Security
Filesystem Security
Database Security
Error Reporting
Using Register Globals
User Submitted Data
Magic Quotes
Hiding PHP
Keeping Current
Features
HTTP authentication with PHP
Cookies
Sessions
Dealing with XForms
Handling file uploads
Using remote files
Connection handling
Persistent Database Connections
Safe Mode
Command line usage
Garbage Collection
DTrace Dynamic Tracing
Function Reference
Affecting PHP's Behaviour
Audio Formats Manipulation
Authentication Services
Command Line Specific Extensions
1 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
Spanish
Sintaxis
2 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
Entrecomillado doble
Si un string est delimitado con comillas dobles ("), PHP interpretar las siguientes secuencias de escape
como caracteres especiales:
Secuencia
\n
\r
\t
\v
\e
\f
\\
\$
\"
\[0-7]{1,3}
\x[0-9AFa-f]{1,2}
\u{[0-9AFa-f]+}
3 de 31
Caracteres escapados
Significado
avance de lnea (LF o 0x0A (10) en ASCII)
retorno de carro (CR o 0x0D (13) en ASCII)
tabulador horizontal (HT o 0x09 (9) en ASCII)
tabulador vertical (VT o 0x0B (11) en ASCII) (desde PHP 5.2.5)
escape (ESC o 0x1B (27) en ASCII) (desde PHP 5.4.4)
avance de pgina (FF o 0x0C (12) en ASCII) (desde PHP 5.2.5)
barra invertida
signo de dlar
comillas dobles
la secuencia de caracteres que coincida con la expresin regular es un carcter en notacin
octal, que silenciosamente desborda para encajar en un byte (p.ej. "\400" === "\000")
la secuencia de caracteres que coincida con la expresin regular es un carcter en notacin
hexadecimal
la secuencia de caracteres que coincida con la expresin regular es un punto de cdigo de
Unicode, la cual ser imprimida al string como dicha representacin UTF-8 del punto de
cdigo (aadido en PHP 7.0.0)
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
Al igual que en el entrecomillado simple de un string, escapar cualquier otro carcter puede dar lugar a
que se muestre tambin la barra invertida. Antes de PHP 5.1.1, no se mostraba la barra invertida de
\{$var}.
La caracterstica ms importante del entrecomillado doble de un string es el hecho de que se expanden los
nombres de las variables. Consulte el anlisis de string para ms detalles.
Heredoc
Una tercera forma de delimitar un string es mediante la sintaxis heredoc: <<<. Despus de este operador,
se deber proporcionar un identificador y justo despus una nueva lnea. A continuacin va el propio
string, y para cerrar la notacin se pone el mismo identificador.
El identificador de cierre debe empezar en la primera columna de la nueva lnea. Asimismo, el identificador
debe seguir las mismas reglas de nomenclatura de las etiquetas en PHP: debe contener solo caracteres
alfanumricos y guiones bajos, y debe empezar con un carcter alfabtico o un guin bajo.
Advertencia
Es muy importante sealar que la lnea con el identificador de cierre no debe contener ningn otro
carcter, excepto un punto y coma (;). Esto, en especial, significa que el identificador no debe estar
sangrado, y que no debe existir ningn espacio ni tabulacin antes o despus del punto y coma. Es muy
importante observar que el primer carcter antes del identificador de cierre debe ser un salto de lnea
definido por el sistema operativo local. Este es \n en los sistemas UNIX, incluyendo Mac OS X. Al
delimitador de cierre le ha de seguir tamben una nueva lnea.
Si se rompe esta regla y el identificador de cierre no est "limpio", no ser considerado como un
identificador de cierre, por lo que PHP continuar buscando uno. Si no se encuentra ningn identificador
de cierre apropiado antes del final del fichero, se producir un error de anlisis en la ltima lnea.
No se puede emplear Heredoc para inicializar las propiedades de una clase. Desde PHP 5.3, esta limitacin
es vlida solamente para un heredoc que contengan variables.
Ejemplo #1 Ejemplo no vlido
<?php
classfoo{
public$bar=<<<EOT
bar
EOT;
}
?>
El texto heredoc se comporta como un string entre comillas dobles, pero sin tener comillas dobles. Esto
significa que no es necesario escapar las comillas en un heredoc, aunque se puede seguir empleando los
cdigos de escape indicados arriba. Pese a que las variables son expandidas, se debe tener el mismo
cuidado al expresar variables complejas en un heredoc que en un string.
Ejemplo #2 Ejemplo de entrecomillado de string en Heredoc
<?php
$str=<<<EOD
Ejemplodeunacadena
expandidaenvariaslneas
empleandolasintaxisheredoc.
EOD;
/*Unejemplomscomplejoconvariables.*/
classfoo
{
var$foo;
var$bar;
functionfoo()
{
$this->foo='Foo';
$this->bar=array('Bar1','Bar2','Bar3');
}
}
$foo=newfoo();
4 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
$nombre='MiNombre';
echo<<<EOT
Minombrees"$nombre".Estoyescribiendounpocode$foo->foo.
Ahora,estoyescribiendounpocode{$foo->bar[1]}.
Estodeberamostraruna'A'mayscula:\x41
EOT;
?>
Tambin se puede emplear la sintaxis Heredoc para pasar datos como argumentos de una funcin:
Ejemplo #3 Ejemplo de Heredoc en argumentos
<?php
var_dump(array(<<<EOD
foobar!
EOD
));
?>
Desde PHP 5.3.0, es posible inicializar variables estticas y propiedades/constantes de clase mediante la
sintaxis Heredoc:
Ejemplo #4 Usar Heredoc para inicializar valores estticos
<?php
//Variablesestticas
functionfoo()
{
static$bar=<<<LABEL
Nadaaqu...
LABEL;
}
//Propiedades/constantesdeclase
classfoo
{
constBAR=<<<FOOBAR
Ejemplodeconstante
FOOBAR;
public$baz=<<<FOOBAR
Ejemplodepropiedad
FOOBAR;
}
?>
Nowdoc
Nowdoc es a los string con comillas simples lo mismo que Heredoc lo es a los string con comillas dobles.
Un nowdoc se especifica de forma anloga a un heredoc, pero no se realiza ningn anlisis dentro del
nowdoc. La construccin es ideal para embeber cdigo de PHP o grandes fragmentos de texto sin
necesidad de escaparlos. Comparte algunas caractersticas comunes con la construccin <![CDATA[ ]]> de
SGML, donde se declara un bloque de texto que no se analiza.
Un nowdoc se identifica con la misma secuencia empleada para heredoc, <<<, pero el identificador que le
5 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
sigue est delimitado con comillas simples, p.ej., <<<'EOT'. Todas las reglas para los identificadores de
heredoc tambin son aplicables a los identificadores de nowdoc, especialmente aquellas que se refieren al
empleo del identificador de cierre.
Ejemplo #6 Ejemplo de entrecomillado de string de Nowdoc
<?php
$str=<<<'EOD'
Ejemplodeunstring
expandidoenvariaslneas
empleandolasintaxisnowdoc.
EOD;
/*Unejemplomscomplejoconvariables.*/
classfoo
{
public$foo;
public$bar;
functionfoo()
{
$this->foo='Foo';
$this->bar=array('Bar1','Bar2','Bar3');
}
}
$foo=newfoo();
$nombre='MiNombre';
echo<<<'EOT'
Minombrees"$nombre".Estoyescribiendounpocode$foo->foo.
Ahora,estoyescribiendounpocode{$foo->bar[1]}.
Estodeberamostraruna'A'mayscula:\x41
EOT;
?>
Nota:
El soporte para Nowdoc se aadi en PHP 5.3.0.
Anlisis de variables
Cuando un string es especificado mediante comillas dobles o mediante heredoc, las variables que haya
dentro de dicho string se analizarn.
Existen dos tipos de sintaxis: una simple y otra compleja. La sintaxis simple es la ms empleada y prctica.
Proporciona una forma de embeber una variable, un valor de un array o una propiedad de un object dentro
de un string con el mnimo esfuerzo.
La sintaxis compleja puede ser reconocida por las llaves que delimitan la expresin.
Sintaxis simple
Si se encuentra un signo de dlar ($), el analizador tomar el mayor nmero de smbolos para formar un
nombre de variable vlido. Delimitar el nombre de la variable con llaves permite especificar explcitamente
6 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
De forma parecida, se puede analizar el ndice de un array o la propiedad de un object. Con los ndices de
los arrays, el corchete de cierre (]) marca el final del ndice. La misma regla se puede aplicar a las
propiedades de los objetos y a las variables simples.
Ejemplo #8 Ejemplo de sintaxis simple
<?php
$jugos=array("manzana","naranja","koolaid1"=>"prpura");
echo"ltomalgodejugode$jugos[0].".PHP_EOL;
echo"ltomalgodejugode$jugos[1].".PHP_EOL;
echo"ltomalgodejugo$jugos[koolaid1].".PHP_EOL;
classpersona{
public$john="JohnSmith";
public$jane="JaneSmith";
public$robert="RobertPaulsen";
public$smith="Smith";
}
$persona=newpersona();
echo"$persona->johntomalgodejugode$jugos[0].".PHP_EOL;
echo"$persona->johnentoncesdijoholaa$persona->jane.".PHP_EOL;
echo"Laesposade$persona->johnsaluda$persona->robert.".PHP_EOL;
echo"$persona->robertsaludalosdos$persona->smiths.";//Nofuncionar
?>
Esta sintaxis no se llama compleja porque sea compleja, sino porque permite el empleo de expresiones
complejas.
Cualquier variable escalar, elemento de array o propiedad de objeto con una representacin de tipo string
puede ser incluido a travs de esta sintaxis. Simplemente se escribe la expresin del mismo modo en que
aparecera por fuera del string, y delimitndola con { y }. Dado que { no puede ser escapado, esta sintaxis
ser reconocida nicamente cuando el $ siga inmediatamente al {. Utilice {\$ para obtener un {$ literal.
Algunos ejemplos para que quede ms claro:
<?php
//Mostrartodosloserrores
error_reporting(E_ALL);
7 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
$genial='fantstico';
//Nofunciona,muestra:Estoes{fantstico}
echo"Estoes{$genial}";
//Funciona,muestra:Estoesfantstico
echo"Estoes{$genial}";
//Funciona
echo"Estecuadradotiene{$cuadrado->width}00centmetrosdelado.";
//Funciona,lasclavesentrecomillasslofuncionanusandolasintaxisdellaves
echo"Estofunciona:{$arr['clave']}";
//Funciona
echo"Estofunciona:{$arr[4][3]}";
//Estonofuncionaporlamismaraznque$foo[bar]esincorrectofueradeunstring.
//Enotraspalabras,anfuncionara,perosolamenteporquePHPprimerobuscauna
//constantellamadafoo;seemitirunerrordenivelE_NOTICE
//(constantenodefinida).
echo"Estoestmal:{$arr[foo][3]}";
//Funciona.Cuandoseusanarraysmultidimensionales,empleesiemprellavesquedelimiten
//alosarrayscuandoseencuentredentrodeunstring
echo"Estofunciona:{$arr['foo'][3]}";
//Funciona.
echo"Estofunciona:".$arr['foo'][3];
echo"Estotambinfunciona:{$obj->valores[3]->nombre}";
echo"Esteeselvalordelavariablellamada$nombre:{${$nombre}}";
echo"EsteeselvalordelavariablellamadaporelvalordevueltoporgetNombre():{${getNombre()}}";
echo"Esteeselvalordelavariablellamadaporelvalordevueltopor\$objeto->getNombre():{${$objeto->getNombre()}}";
//Nofunciona,muestra:EstoeselvalordevueltoporgetNombre():{getNombre()}
echo"EstoeselvalordevueltoporgetNombre():{getNombre()}";
?>
Con esta sintaxis, tambin es posible acceder a las propiedades de una clase empleando variables dentro
de un string.
<?php
classfoo{
var$bar='Soybar.';
}
$foo=newfoo();
$bar='bar';
$baz=array('foo','bar','baz','quux');
echo"{$foo->$bar}\n";
echo"{$foo->{$baz[1]}}\n";
?>
Nota:
Las funciones, llamadas a mtodos, variables de clase estticas y constantes de clases dentro de
{$} funcionan desde PHP 5. Sin embargo, el valor accedido puede ser interpretado como el
nombre de la variable en el mbito en el que est definido el string. El empleo de simples llaves
({}) no servir para acceder al valor devuelto por las funciones o mtodos, o los valores de las
8 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
A partir de PHP 5.4, los ndices de string tienen que ser de tipo integer o integer en forma de string, si no,
se emitir una advertencia. Anteriormente, un ndice como "foo" era convertido de manera silenciosa a 0.
Ejemplo #10 Diferencias entre PHP 5.3 y PHP 5.4
<?php
$str='abc';
9 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
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']));
?>
Nota:
El acceso a variables de otros tipos (sin incluir arrays u objetos que implementen las interfaces
apropiadas) utilizando [] o {}, silenciosamente retorna NULL.
Nota:
PHP 5.5 aadi soporte para acceder a caracteres dentro de literales de tipo string utilizando [] o
{}.
Conversin a string
Un valor puede convertirse a un string empleando el molde (string) o mediante la funcin strval(). La
conversin automtica a string tiene lugar en el mbito de una expresin donde sea necesario un string.
Esto ocurre cuando se utilizan las funciones echo o print, o cuando se compara una variable con un string.
Las secciones sobre Tipos y Manipulacin de tipos lo aclararn. Consulte tambin la funcin settype().
El valor TRUE del tipo boolean es convertido al string "1". El valor FALSE del tipo boolean es convertido al
string "" (el string vaco). Esto permite la conversin en ambos sentidos entre los valores de los tipos
10 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
boolean y string.
Un integer o float es convertido a un string que representa textualmente el nmero (incluyendo la parte
exponencial para los float. Los nmeros de punto flotante pueden ser convertidos mediante la notacin
exponencial (4.1E+6).
Nota:
El carcter para el punto decimal se define en el localismo del script (categora LC_NUMERIC).
Consulte la funcin setlocale().
Los arrays siempre son convertidos al string "Array". Debido a esto, echo y print no pueden por s mismos
mostrar el contenido de un array. Para ver un nico elemento individualmente, utilice una construccin
como echo $arr['foo']. Vea los consejos de ms abajo para mostrar el contenido completo.
Los object en PHP 4 siempre son convertidos al string "Object". Para mostrar los valores de las
propiedades de un objeto para su depuracin, lea los prrafos siguientes. Para obtener el nombre de la
clase de un objeto, emplee la funcin get_class(). A partir de PHP 5, se puede emplear el mtodo __toString
cuando sea relevante.
Un resource siempre es convertido a string con la estructura "Resource id #1", donde 1 es el nmero de
recurso asignado al resource por PHP durante la ejecucin. A pesar de que no se debe depender de la
estructura exacta, debido a que est sujeta a cambios, siempre ser nica para un recurso dado dentro del
tiempo de vida de un script en ejecucin (es decir, una peticin web o proceso CLI), por lo que no ser
reutilizada. Para obtener el tipo de un resource, emplee la funcin get_resource_type().
NULL
Para ms informacin sobre esta conversin, consulte la pgina del manual de Unix para a strtod(3).
Para probar cualesquiera de los ejemplos de esta seccin, copie y pguelos e incluya la siguiente lnea para
ver lo que est sucediendo:
<?php
echo"\$foo==$foo;tipo:".gettype($foo)."<br/>\n";
?>
No espere obtener el cdigo de un carcter convirtindolo a un integer, como ocurre en C. Emplee las
11 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
funciones ord() y chr() para convertir entre cdigo cdigos ASCII y caracteres.
12 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
This works:
<?php
$foo = <<<END
abcd
END;
?>
This does not:
<?php
foo(<<<END
abcd
END;
);
// syntax error, unexpected ';'
?>
Without semicolon, it works fine:
<?php
foo(<<<END
abcd
END
);
?>
up
down
9
John
2 months ago
Ive been a PHP programmer for a decade, and Ive always been using the single-quoted literal and periodconcatenation method of string creation. But I wanted to answer the performance question once and for all, using
sufficient numbers of iterations and a modern PHP version. For my test, I used:
php -v
PHP 7.0.12 (cli) (built: Oct 14 2016 09:56:59) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
------ Results: ------* 100 million iterations:
$outstr = 'literal' . $n . $data . $int . $data . $float . $n;
63608ms (34.7% slower)
$outstr = "literal$n$data$int$data$float$n";
47218ms (fastest)
$outstr =<<<EOS
literal$n$data$int$data$float$n
EOS;
47992ms (1.64% slower)
$outstr = sprintf('literal%s%s%d%s%f%s', $n, $data, $int, $data, $float, $n);
76629ms (62.3% slower)
$outstr = sprintf('literal%s%5$s%2$d%3$s%4$f%s', $n, $int, $data, $float, $data, $n);
96260ms (103.9% slower)
* 10 million iterations (test adapted to see which of the two fastest methods were faster at adding a newline; either the
PHP_EOL literal, or the \n string expansion):
$outstr = 'literal' . $n . $data . $int . $data . $float . $n;
6228ms (reference for single-quoted without newline)
$outstr = "literal$n$data$int$data$float$n";
13 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
up
down
15
garbage at iglou dot eu
7 months 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[0]);
// Return string(1) "S"
// -- With array cast -var_dump((array) $a);
// Return array(1) { [0]=> string(17) "String array test"}
14 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
var_dump((array) $a[0]);
// Return string(17) "S"
- Norihiori
up
down
1
nospam at nospam dot com
3 months ago
Beware that consistent with "String conversion to numbers":
<?php
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.
?>
up
down
12
chAlx at findme dot if dot u dot need
8 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:
<?php
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)
?>
up
down
9
php at richardneill dot org
3 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().
up
down
10
lelon at lelon dot net
12 years ago
You can use the complex syntax to put the value of both object properties AND object methods inside a string. For
example...
<?php
class Test {
public $one = 1;
public function two() {
return 2;
15 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
}
}
$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 '$'.
<?php
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.
up
down
8
headden at karelia dot ru
7 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:
<?php
// 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(...)}
?>
up
down
9
atnak at chejz dot com
12 years ago
Here is a possible gotcha related to oddness involved with accessing strings by character past the end of the string:
$string = 'a';
var_dump($string[2]); // string(0) ""
var_dump($string[7]); // string(0) ""
$string[7] === ''; // TRUE
It appears that anything past the end of the string gives an empty string.. However, when E_NOTICE is on, the above
examples will throw the message:
Notice: Uninitialized string offset: N in FILE on line LINE
This message cannot be specifically masked with @$string[7], as is possible when $string itself is unset.
isset($string[7]); // FALSE
$string[7] === NULL; // FALSE
16 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
Even though it seems like a not-NULL value of type string, it is still considered unset.
up
down
1
ksean
4 months ago
$foo = 'foo';
echo "{$foo}"; // foo
echo "${'fo' . 'o'}"; // foo
echo "{$'fo' . 'o'}"; // error
up
down
6
og at gams dot at
9 years ago
easy transparent solution for using constants in the heredoc format:
DEFINE('TEST','TEST STRING');
$const = get_defined_constants();
echo <<<END
{$const['TEST']}
END;
Result:
TEST STRING
up
down
4
rkfranklin+php at gmail dot com
9 years ago
If you want to use a variable in an array index within a double quoted string you have to realize that when you put the
curly braces around the array, everything inside the curly braces gets evaluated as if it were outside a string. Here
are some examples:
<?php
$i = 0;
$myArray[Person0] = Bob;
$myArray[Person1] = George;
// prints Bob (the ++ is used to emphasize that the expression inside the {} is really being evaluated.)
echo "{$myArray['Person'.$i++]}<br>";
// these print George
echo "{$myArray['Person'.$i]}<br>";
echo "{$myArray["Person{$i}"]}<br>";
// These don't work
echo "{$myArray['Person$i']}<br>";
echo "{$myArray['Person'$i]}<br>";
// These both throw fatal errors
// echo "$myArray[Person$i]<br>";
//echo "$myArray[Person{$i}]<br>";
?>
up
down
0
mark at manngo dot net
9 days 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:
17 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
<?php
$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:
<?php
print "This is a $fruit[a]"; // unquote the key
print "This is a ${fruit['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.
Its 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 ?
up
down
1
shd at earthling dot net
7 years ago
If you want a parsed variable surrounded by curly braces, just double the curly braces:
<?php
$foo = "bar";
echo "{{$foo}}";
?>
will just show {bar}. The { is special only if followed by the $ sign and matches one }. In this case, that applies only
to the inner braces. The outer ones are not escaped and pass through directly.
up
down
0
dee jay simple 0 0 7 at ge mahl dot com
5 years ago
I recently discovered the joys of using heredoc with sprintf and positions. Useful if you want some code to iterate, you
can repeat placeholders.
<?php
function getNumber($num = 0) {
$foo = rand(1,20);
return ($foo + $num);
}
function getString() {
$foo = array("California","Oregon","Washington");
shuffle($foo);
return $foo[0];
}
function getDiv() {
$num = getNumber();
$div = sprintf( "<div>%s</div>", getNumber(rand(-5,5)) );
return $div;
}
$string = <<<THESTRING
I like the state of %1\$s <br />
I picked: %2\$d as a number, <br />
I also picked %2\$d as a number again <br />
%3\$s<br />
18 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
%3\$s<br />
%3\$s<br />
%3\$s<br />
%3\$s<br />
THESTRING;
$returnText = sprintf( $string, getString(),getNumber(),getDiv() );
echo $returnText;
?>
Expected output of the above code:
I like the state of Oregon
I picked: 15 as a number,
I also picked 15 as a number again
5
5
5
5
5
up
down
1
webmaster at rephunter dot net
11 years ago
Use caution when you need white space at the end of a heredoc. Not only is the mandatory final newline before the
terminating symbol stripped, but an immediately preceding newline or space character is also stripped.
For example, in the following, the final space character (indicated by \s -- that is, the "\s" is not literally in the
text, but is only used to indicate the space character) is stripped:
$string = <<<EOT
this is a string with a terminating space\s
EOT;
In the following, there will only be a single newline at the end of the string, even though two are shown in the text:
$string = <<<EOT
this is a string that must be
followed by a single newline
EOT;
up
down
0
Evan K
8 years ago
I encountered the odd situation of having a string containing unexpanded escape sequences that I wanted to expand, but
also contained dollar signs that would be interpolated as variables. "$5.25\n", for example, where I want to convert \n
to a newline, but don't want attempted interpolation of $5.
Some muddling through docs and many obscenties later, I produced the following, which expands escape sequences in an
existing string with NO interpolation.
<?php
// where we do all our magic
function expand_escape($string) {
return preg_replace_callback(
'/\\\([nrtvf]|[0-7]{1,3}|[0-9A-Fa-f]{1,2})?/',
create_function(
'$matches',
'return ($matches[0] == "\\\\") ? "" : eval( sprintf(\'return "%s";\', $matches[0]) );'
19 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
),
$string
);
}
// a string to test, and show the before and after
$before = 'Quantity:\t500\nPrice:\t$5.25 each';
$after = expand_escape($before);
var_dump($before, $after);
/* Outputs:
string(34) "Quantity:\t500\nPrice:\t$5.25 each"
string(31) "Quantity: 500
Price: $5.25 each"
*/
?>
up
down
-1
bishop
10 years ago
up
down
-2
steve at mrclay dot org
8 years ago
20 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
up
down
-2
harmor
8 years ago
up
down
-4
cvolny at gmail dot com
8 years ago
21 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
up
down
-8
m021 at springtimesoftware dot com
4 years ago
Heredoc literals delete any trailing space (tabs and blanks) on each line. This is unexpected, since quoted strings do
not do this. This is probably done for historical reasons, so would not be considered a bug.
up
down
-1
user at grantsearch dot com dot au
8 months ago
up
down
-7
saamde at gmail dot com
6 years ago
Watch out for the "unexpected T_SL" error. This appears to occur when there is white space just after "<<<EOT" and since
it's white space it's real hard to spot the error in your code.
up
down
-5
necrodust44 at gmail dot com
2 years ago
22 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
up
down
-7
Denis R.
4 years ago
up
down
-9
mcamiano at ncsu dot edu
4 years ago
up
down
-8
Richard Neill
9 years ago
up
down
-8
Liesbeth
7 years ago
If you need to emulate a nowdoc in PHP < 5.3, try using HTML mode and output capturing. This way '$' or '\n' in your
string won't be a problem anymore (but unfortunately, '<?' will be).
23 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
up
down
-9
Jonathan Lozinski
12 years ago
up
down
-10
DELETETHIS dot php at dfackrell dot mailshell dot com
11 years ago
24 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
up
down
-11
"Sascha Ziemann"
7 years ago
up
down
-11
Michael
5 years ago
up
down
-15
Obeliks
8 years ago
up
down
-6
espertalhao04 at hotmail dot com
3 years ago
gtisza at gmail dot com
You incorrectly stated that thee documentation doesn't refer anything about the semicolon at the end of the heredocs and
nowdocs being interpreted as a "real" semicolon.
25 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
up
down
-11
www.feisar.de
12 years ago
watch out when comparing strings that are numbers. this example:
<?php
26 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
up
down
-15
penda ekoka
9 years ago
up
down
-14
sgbeal at googlemail dot com
5 years ago
up
down
-19
Ultimater at gmail dot com
5 years ago
27 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
up
down
-13
Anonymous
2 years ago
$my_int = "12,140";
28 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
echo 1 + $my_int ;
Returns 13 not the expected 12141
up
down
-18
fmouse at fmp dot com
9 years ago
up
down
-5
sideshowAnthony at googlemail dot com
10 months ago
up
down
-17
benl39 at free dot fr
2 years ago
up
down
-15
Ray.Paseur often uses Gmail
2 years ago
In Example #8, above, consider the risk to the script if a programmer were to define('koolaid1', 'XYZ'); For this reason
it's wise to use quotes around literal-string associative array keys. As written without quotes, PHP should raise a
Notice.
up
down
-37
Salil Kothadia
8 years ago
An interesting finding about Heredoc "syntax error, unexpected $end".
I got this error because I did not use the php close tag "?>" and I had no code after the heredoc code.
29 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
up
down
-15
cnbk201 at gmail dot com
2 years ago
add a note
Tipos
Introduccin
Booleanos
Nmeros enteros (Integers)
Nmeros de punto flotante
Cadenas de caracteres (Strings)
Arrays
Objetos
Recursos
NULO
Llamadas de retorno (Callbacks / Callables)
Seudotipos y variables usadas en esta documentacin
Manipulacin de tipos
Copyright 2001-2017 The PHP Group
My PHP.net
Contact
Other PHP.net sites
Mirror sites
30 de 31
14/01/17 15:29
http://php.net/manual/es/language.types.string.php
Privacy policy
31 de 31
14/01/17 15:29