Строки

Строка - это набор символов. В PHP символ это то же самое, что и байт, это значит, что возможно ровно 256 различных символов. Это также означает, что PHP не имеет встроенной поддержки Unicode'а. Некоторую поддержку Unicode'а обеспечивают функции utf8_encode() и utf8_decode().

Замечание: Нет никаких проблем, если строка очень велика. Практически не существует ограничений на размер строк, налагаемых PHP, так что нет абсолютно никаких причин беспокоиться об их длине.

Синтаксис

Строка может быть определена тремя различными способами.

Одинарные кавычки

Простейший способ определить строку - это заключить ее в одинарные кавычки (символ ').

Чтобы использовать одинарную кавычку внутри строки, как и во многих других языках, ее необходимо предварить символом обратной косой черты (\), т. е. экранировать ее. Если обратная косая черта должна идти перед одинарной кавычкой либо быть в конце строки, вам необходимо продублировать ее. Обратите внимание, что если вы попытаетесь экранировать любой другой символ, обратная косая черта также будет напечатана! Так что, как правило, нет необходимости экранировать саму обратную косую черту.

Замечание: В PHP 3 в данном случае будет выдано сообщение уровня E_NOTICE.

Замечание: В отличие от двух других синтаксисов, переменные и экранирующие последовательности для специальных символов, встречающиеся в строках, заключенных в одинарные кавычки, не обрабатываются.

<?php
echo 'это простая строка';

echo
'Также вы можете вставлять в строки
символ новой строки таким образом,
поскольку это нормально'
;

// Выведет: Однажды Арнольд сказал: "I'll be back"
echo 'Однажды Арнольд сказал: "I\'ll be back"';

// Выведет: Вы удалили C:\*.*?
echo 'Вы удалили C:\\*.*?';

// Выведет: Вы удалили C:\*.*?
echo 'Вы удалили C:\*.*?';

// Выведет: Это не вставит: \n новую строку
echo 'Это не вставит: \n новую строку';

// Выведет: Переменные $expand также $either не подставляются
echo 'Переменные $expand также $either не подставляются';
?>

Двойные кавычки

Если строка заключена в двойные кавычки ("), PHP распознает большее количество управляющих последовательностей для специальных символов:

Таблица 11-1. Управляющие последовательности

последовательностьзначение
\nновая строка (LF или 0x0A (10) в ASCII)
\rвозврат каретки (CR или 0x0D (13) в ASCII)
\tгоризонтальная табуляция (HT или 0x09 (9) в ASCII)
\\обратная косая черта
\$знак доллара
\"двойная кавычка
\[0-7]{1,3} последовательность символов, соответствующая регулярному выражению, символ в восьмеричной системе счисления
\x[0-9A-Fa-f]{1,2} последовательность символов, соответствующая регулярному выражению, символ в шестнадцатеричной системе счисления

Повторяем, если вы захотите мнемнонизировать любой другой символ, обратная косая черта также будет напечатана!

Но самым важным свойством строк в двойных кавычках является обработка переменных. Смотрите более подробно: обработка строк.

Heredoc

Другой способ определения строк - это использование heredoc-синтаксиса ("<<<"). После <<< необходимо указать идентификатор, затем идет строка, а потом этот же идентификатор, закрывающий вставку.

Закрывающий идентификатор должен начинаться в первом столбце строки. Кроме того, идентификатор должен соответствовать тем же правилам именования, что и все остальные метки в PHP: содержать только буквенно-цифровые символы и знак подчеркивания, и должен начинаться с нецифры или знака подчеркивания.

Внимание

Очень важно отметить, что строка с закрывающим идентификатором не содержит других символов, за исключением, возможно, точки с запятой (;). Это означает, что идентификатор не должен вводиться с отступом и что не может быть никаких пробелов или знаков табуляции до или после точки с запятой. Важно также понимать, что первым символом перед закрывающим идентификатором должен быть символ новой строки, определенный в вашей операционной системе. Например, на Macintosh это \r.

Если это правило нарушено и закрывающий идентификатор не является "чистым", считается, что закрывающий идентификатор отсутствует и PHP продолжит его поиск дальше. Если в этом случае верный закрывающий идентификатор так и не будет найден, то это вызовет ошибку в обработке с номером строки в конце скрипта.

Heredoc-текст ведет себя так же, как и строка в двойных кавычках, при этом их не имея. Это означает, что вам нет необходимости экранировать кавычки в heredoc, но вы по-прежнему можете использовать вышеперечисленные управляющие последовательности. Переменные обрабатываются, но с применением сложных переменных внутри heredoc нужно быть также внимательным, как и при работе со строками.

Пример 11-2. Пример определения heredoc-строки

<?php
$str
= <<<EOD
Пример строки,
охватывающей несколько строчек,
с использованием heredoc-синтаксиса.
EOD;

/* Более сложный пример с переменными. */
class foo
{
   var
$foo;
   var
$bar;

   function
foo()
   {
      
$this->foo = 'Foo';
      
$this->bar = array('Bar1', 'Bar2', 'Bar3');
   }
}

$foo = new foo();
$name = 'МоеИмя';

echo <<<EOT
Меня зовут "$name". Я печатаю $foo->foo.
Теперь я вывожу
{$foo->bar[1]}.
Это должно вывести заглавную букву 'A':
\x41
EOT;
?>

Замечание: Поддержка heredoc была добавлена в PHP 4.

Обработка переменных

Если строка определяется в двойных кавычках, либо при помощи heredoc, переменные внутри нее обрабатываются.

Существует два типа синтаксиса: простой и сложный. Простой синтаксис более легок и удобен. Он дает возможность обработки переменной, значения массива (array) или свойства объекта (object).

Сложный синтаксис был введен в PHP 4 и может быть распознан по фигурным скобкам, окружающих выражение.

Простой синтаксис

Если интерпретатор встречает знак доллара ($), он захватывает так много символов, сколько возможно, чтобы сформировать правильное имя переменной. Если вы хотите точно определить конец имени, заключайте имя переменной в фигурные скобки.

<?php
$beer
= 'Heineken';
echo
"$beer's taste is great"; // работает, "'" это неверный символ для имени переменной
echo "He drank some $beers"// не работает, 's' это верный символ для имени переменной
echo "He drank some ${beer}s"; // работает
echo "He drank some {$beer}s"; // работает
?>

Точно также могут быть обработаны элемент массива (array) или свойство объекта (object). В индексах массива закрывающая квадратная скобка (]) обозначает конец определения индекса. Для свойств объекта применяются те же правила, что и для простых переменных, хотя с ними невозможен трюк, как с переменными.

<?php
// Эти примеры специфически об использовании массивов внутри
// строк. Вне строк всегда заключайте строковые ключи вашего
// массива в кавычки и не используйте вне строк {скобки}.

// Давайте покажем все ошибки
error_reporting(E_ALL);

$fruits = array('strawberry' => 'red', 'banana' => 'yellow');

// Работает, но заметьте, что вне кавычек строки это работает по-другому
echo "A banana is $fruits[banana].";

//Работает
echo "A banana is {$fruits['banana']}.";

// Работает, но PHP, как описано ниже, сначала ищет
// константу banana.
echo "A banana is {$fruits[banana]}.";

// Не работает, используйте фигурные скобки. Это вызовет ошибку обработки.
echo "A banana is $fruits['banana'].";

// Работает
echo "A banana is " . $fruits['banana'] . ".";

// Работает
echo "This square is $square->width meters broad.";

// Не работает. Для решения см. сложный синтаксис.
echo "This square is $square->width00 centimeters broad.";
?>

Для чего-либо более сложного вы должны использовать сложный синтаксис.

Сложный (фигурный) синтаксис

Он называется сложным не потому, что труден в понимании, а потому что позволяет использовать сложные выражения.

Фактически, вы можете включить любое значение, находящееся в пространстве имени в строке с этим синтаксисом. Вы просто записываете выражение таким же образом, как и вне строки, а затем заключаете его в { и }. Поскольку вы не можете экранировать '{', этот синтаксис будет распознаваться только когда $ следует непосредственно за {. (Используйте "{\$" или "\{$" чтобы отобразить "{$"). Несколько поясняющих примеров:

<?php
// Давайте покажем все ошибки
error_reporting(E_ALL);

$great = 'fantastic';

// Не работает, выведет: This is { fantastic}
echo "This is { $great}";

// Работает, выведет: This is fantastic
echo "This is {$great}";
echo
"This is ${great}";

// Работает
echo "Этот квадрат шириной {$square->width}00 сантиметров.";

// Работает
echo "Это работает: {$arr[4][3]}";

// Это неверно по той же причине, что и $foo[bar] неверно вне
// строки. Другими словами, это по-прежнему будет работать,
// но поскольку PHP сначала ищет константу foo, это вызовет
// ошибку уровня E_NOTICE (неопределенная константа).
echo "Это неправильно: {$arr[foo][3]}";

// Работает. При использовании многомерных массивов, внутри
// строк всегда используйте фигурные скобки
echo "Это работает: {$arr['foo'][3]}";

// Работает.
echo "Это работает: " . $arr['foo'][3];

echo
"Вы даже можете записать {$obj->values[3]->name}";

echo
"Это значение переменной по имени $name: {${$name}}";
?>

Доступ к символу в строке и его изменение

Символы в строках можно использовать и модифицировать, определив их смещение относительно начала строки, начиная с нуля, в фигурных скобках после строки.

Замечание: Для обеспечения обратной совместимости, вы по-прежнему имеете возможность использовать в тех же целях скобки массива. Однако, начиная с PHP 4, этот синтаксис нежелателен к использованию.

Пример 11-3. Несколько примеров строк

<?php
// Получение первого символа строки
$str = 'Это тест.';
$first = $str{0};

// Получение третьего символа строки
$third = $str{2};

// Получение последнего символа строки
$str = 'Это все еще тест.';
$last = $str{strlen($str)-1};

// Изменение последнего символа строки
$str = 'Посмотри на море';
$str{strlen($str)-1} = 'я';

?>

Полезные функции и операторы

Строки могут быть объединены при помощи оператора '.' (точка). Обратите внимание, оператор сложения '+' здесь не работает. Дополнительную информацию смотрите в разделе Строковые операторы.

Для модификации строк существует множество полезных функций.

Основные функции описаны в разделе строковых функций, функции регулярных выражений для расширенного поиска и замены (в двух частях: Perl и POSIX расширенный).

Также существуют функции для URL-строк, и функции для шифрования/дешифрования строк (mcrypt и mhash).

Наконец, если вы все еще не нашли, что искали, смотрите также функции для символьного типа.

Преобразование в строку

Вы можете преобразовать значение в строку, используя приведение (string), либо функцию strval(). В выражениях, где необходима строка, преобразование происходит автоматически. Это происходит, когда вы используете функции echo() или print(), либо когда вы сравниваете значение переменной со строкой. Прочтение разделов руководства Типы и Манипуляции с типами сделает следующее более понятным. Смотрите также settype().

Булево (boolean) значение TRUE преобразуется в строку "1", а значение FALSE представляется как "" (пустая строка). Этим способом вы можете преобразовывать значения в обе стороны - из булева типа в строковый и наоборот.

Целое (integer) или число с плавающей точкой (float) преобразуется в строку, представленную числом, состоящим из его цифр (включая показатель степени для чисел с плавающей точкой).

Массивы всегда преобразуются в строку "Array", так что вы не можете отобразить содержимое массива (array), используя echo() или print(), чтобы узнать, что он содержит. Чтобы просмотреть один элемент, вам нужно сделать что-то вроде echo $arr['foo']. Смотрите ниже советы о том, как отобразить/просмотреть все содержимое.

Объекты всегда преобразуются в строку "Object". Если вы хотите вывести значение переменной-члена объекта (object) с целью отладки, прочтите следующие абзацы. Если вы хотите получить имя класса требуемого объекта, используйте get_class().

Ресурсы всегда преобразуются в строки со структурой "Resource id #1", где 1 - это уникальный номер ресурса (resource), присвоенный ему PHP во время выполнения. Если вы хотите получить тип ресурса, используйте get_resource_type().

NULL всегда преобразуется в пустую строку.

Как вы могли видеть выше, вывод массивов, объектов или ресурсов не предоставляет вам никакой полезной информации о самих значениях. Более подходящий способ вывода значений для отладки - использовать функции print_r() и var_dump().

Вы также можете преобразовать значения PHP в строки для постоянного хранения. Этот метод называется сериализацией и может быть выполнен при помощи функции serialize(). Кроме того, если в вашей установке PHP есть поддержка WDDX, вы можете сериализовать значения PHP в структуры XML.

Преобразование строк в числа

Если строка распознается как числовое значение, результирующее значение и тип определяется так как показано далее.

Строка будет распознана как float, если она содержит любой из символов '.', 'e', или 'E'. Иначе она будет определена как целое.

Значение определяется по начальной части строки. Если строка начинается с верного числового значения, будет использовано это значение. Иначе значением будет 0 (ноль). Верное числовое значение - это одна или более цифр (могущих содержать десятичную точку), по желанию предваренных знаком, с последующим необязательным показателем степени. Показатель степени - это 'e' или 'E' с последующими одной или более цифрами.

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

Более подробную информацию об этом преобразовании смотрите в разделе о strtod(3) документации Unix.

Если вы хотите протестировать любой из примеров этого раздела, вы можете скопировать и вставить его и следующую строку, чтобы увидеть, что происходит:

<?php
echo "\$foo==$foo; тип: " . gettype ($foo) . "<br />\n";
?>

Не ожидайте получить код символа, преобразовав его в целое (как вы могли бы сделать, например, в C). Для преобразования символов в их коды и обратно используйте функции ord() и chr().



Строки
umeetsriram at yahoo dot com
30-May-2006 04:03
The string can be viewed as an array.

if i say $str = 'string'

echo $str[0] // will print s
echo $str[1] //will print t

It cannot be used as double dimentional array.

If the string is appended with an array

$str.array(1,2);
echo $str will output stringArray

echo $str[6] will print 'A'
alex dot baldacchino at email dot it
16-May-2006 07:42
A little note on variables types and automatic cast in context, when used in statements other than assignment ones (that is when passed to a function, when elaborated on the right of the "=" sign, when a "property" is recalled by the mean of an operator - such us indexed access - and so on): I don't think that's right to say php is typeless or not fully typed, it is yet, but types are not statically determined, instead they're dynamically inferred during execution. This mean that each time a value is elaborated to be assigned to a variable, the value type became the variable type, and if such operation involves an operator allowing different types, a proper type cast occurs, but any variable type on the right side of the assignment operator is left untuched (unless the operator implies an assignment, like incrementing/decrementing ones).

In other words, and generally speaking about languages with dynamic, runtime inferred types, every time I assign a value to a variable, its type changes according to the computed value, but in a cast without self-assignment no cast should happen, instead a temporary variable should be created with the right type and converted value assigned to that; if an operator is not defined for a type, but a cast is possible to any allowed type, if no self assignment occurs, no type cast occurs as well, thus the unability to access an integer by index as it whould be a string.

A possible test:

<?php

$int_var
= 5;
echo
"\\n int_var is of type: ".gettype($int_var);

$str_var = "12";
echo
"\\n str_var is of type: ".gettype($str_var);

$temp_int = (int) $str_var;
echo
"\\n temp_int is of type: ".gettype($temp_int)." and has value: $temp_int";
echo
"\\n str_var after casting on the right of '=' sign is of type: ".gettype($str_var);

$addition = $int_var + $str_var;
echo
"\\n addition has value: $addition; $str_var after addition is of type: ".gettype($str_var);

$str_var = $temp_int;
echo
"\\n str_var after another assignment is of type: ".gettype($str_var);

?>

What does it happen?
bishop
28-Mar-2006 12:58
You may use heredoc syntax to comment out large blocks of code, as follows:
<?php
<<<_EOC
    // end-of-line comment will be masked... so will regular PHP:
   echo ($test == 'foo' ? 'bar' : 'baz');
   /* c-style comment will be masked, as will other heredocs (not using the same marker) */
   echo <<<EOHTML
This is text you'll never see!       
EOHTML;
   function defintion($params)
{
       echo 'foo';
  
}
   class definition extends nothing   
{
       function definition($param)
{
         echo 'do nothing';
      
}     
  
}

   how about syntax errors?; = gone, I bet.
_EOC;
?>

Useful for debugging when C-style just won't do.  Also useful if you wish to embed Perl-like Plain Old Documentation; extraction between POD markers is left as an exercise for the reader.

Note there is a performance penalty for this method, as PHP must still parse and variable substitute the string.
justin at aers dot ne dot spam dot pas dot ca
16-Mar-2006 03:57
RE: www.feisar.de

The example posted in the note, as well as the follow up...

(posted here for reference)
<?php

$x1
= '111111111111111111';
$x2 = '111111111111111112';

echo (
$x1 == $x2) ? "true\n" : "false\n";

?>

...now returns false as of php 4.4.x and beyond. This may have been a bug in 4.3.x, as it *does* return true in all the v. 4.3.x machines we tested it on.

This is not to say that it would no longer be smart to do a strict comparison with ===, but the example above seems to now function as one would expect.
Per Persson
08-Feb-2006 12:39
Although the manual sounds as you could use almost arbitrary expressions in "...{$...}...", actually you can't. However, I have proposed this possibility:
http://www.zend.com/phorum/read.php?num=6&id=655&loc=0&thread=655
adam at obledesign dot com
21-Jan-2006 12:51
If you really want to get constants inside your string you can do something like this (PHP5 only).

<?php

class GetConstant {
 public function
__get($constant_name) {
  return (
defined($constant_name) ? constant($constant_name) : NULL);
 }
}

$C = new GetConstant();

define('FOO','bar');

echo(
"I want a candy {$C->FOO}.");

?>
csaba at alum dot mit dot edu
31-Dec-2005 03:15
Multiline strings:
In most of the strings on this doc page, the heredoc form (<<<) is not needed.  The heredoc form is useful when you also want to embed, without escaping, quotes of the same type as the starting quote.  The single quote form is particularly useful when you want to specify multiline code for future evaluation.

<?php
$code
= '
  $output = "Mutliline output";
  $out = "$output within multiline code:
$ needs escaping within \$out,
and double quotes (\") need escaping within \$out,
but single quotes (\') need escaping everywhere.";
  // Next two lines work with php.exe
  /* on Windows systems */
  $oWSH = new COM("WScript.Shell");
  $oWSH->Popup($out, 4, \'IO Demo\', 131120);
'
;
print
"<pre>$code</pre>";
call_user_func (create_function('', $code));
?>

Happy New Year,
Csaba Gabor from Vienna
18-Dec-2005 06:10
RE  www.feisar.de
<?php

$x1
= '111111111111111111';
$x2 = '111111111111111112';

echo (
$x1 == $x2) ? "true\n" : "false\n";

?> // prints true;

You are right about need to use === to force a string to string comparison.

However as the number exceed the 32 bit range PHP is comparing the floating point not the integer values. 

Both have a float values of 1.11111111111E+017
wilkinson98 at hotmail dot com
17-Dec-2005 05:53
You can't depend on hex in strings to be converted.

<?php

// prints 17
echo 1 + '0x10';   

// prints 0
echo (int) '0x10';
                    
?>
Alex
09-Dec-2005 11:24
For heredocs, the manual is accurate.  Many other descriptions on the web are not.

PHP always tries to evaluate variables.  So if you want a $ sign, it always needs to be escaped or in complex format, depending on the context.  This is especially important if you are trying to do an eval().

<?php
   $foo
= 1;
  
$code = <<<CODE
$bar = $foo;
CODE;
   eval (
$code);    // doesn't work
?>

<?php
   $foo
= 1;
  
$code = <<<CODE
\$
bar = \$foo;
CODE;
   eval (
$code);    // $bar = $foo;
?>

<?php
   $foo
= 1;
  
$code = <<<CODE
\$
bar = {$foo};
CODE;
   eval (
$code);    // $bar = 1;
?>

<?php
   $foo
= 1;
  
$code = <<<CODE
{
$bar} = {$foo};
CODE;
   eval (
$code);    // doesn't work
?>
webmaster at rephunter dot net
30-Nov-2005 08:57
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;
DELETETHIS dot php at dfackrell dot mailshell dot com
01-Nov-2005 08:05
Just some quick observations on variable interpolation:

Because PHP looks for {? to start a complex variable expression in a double-quoted string, you can call object methods, but not class methods or unbound functions.

This works:

<?php
class a {
   function
b() {
       return
"World";
   }
}
$c = new a;
echo
"Hello {$c->b()}.\n"
?>

While this does not:

<?php
function b() {
   return
"World";
}
echo
"Hello {b()}\n";
?>

Also, it appears that you can almost without limitation perform other processing within the argument list, but not outside it.  For example:

<?
$true
= true;
define("HW", "Hello World");
echo
"{$true && HW}";
?>

gives: Parse error: parse error, unexpected T_BOOLEAN_AND, expecting '}' in - on line 3

There may still be some way to kludge the syntax to allow constants and unbound function calls inside a double-quoted string, but it isn't readily apparent to me at the moment, and I'm not sure I'd prefer the workaround over breaking out of the string at this point.
php at simoneast dot NOSPAM dot net
12-Sep-2005 03:17
Be ULTRA careful when multiplying numbers like '1,000'.  If it's a string with a thousands separator like that, PHP ignores everything after the comma.

<?
echo "2,500" * 2;        // displays 4
echo "20,50" * 2;        // displays 4
echo "2,500.00" * 2;    // displays 4

is_numeric("2,500");    // false
?>

I was developing a shopping cart, and had items worth over $1,000 advertised as $1!  Luckily we realised before launch.
Don
28-Aug-2005 06:24
I found this very helpful:

http://shiflett.org/archive/140
diannes at dbfields dot com
21-Jun-2005 01:41
I was trying to perform a series of manipulations on a string  and found that there doesn't seem to be any easy way to force variable expansion to occur if a string hadn't originally been created as double-quoted or heredoc. Maybe there's an easier workaround than the one below, but it's what I ended up doing.
-------------------------------
$var = '5';
$str = "var = $var ";
echo $str;        // prints 'var = "5" ' (expected result)
$str = 'var = "$var" ';
echo $str;        // prints 'var = "$var" ' (expected result)

// NO VARIABLE EXPANSION:

$str = 'var = "$var" ';
echo $str;        // prints 'var = "$var" '
echo "$str";      // prints 'var = "$var" '
$str = "$str";
echo $str;        // still prints 'var = "$var" '
$str = (string)$str;
echo $str;        // still prints 'var = "$var" '
$str = strval($str);
echo $str;        // still prints 'var = "$var" '

// NO VARIABLE EXPANSION THIS WAY EITHER:

$str = 'var = "{$var}" ';
// yields similar results to above

// NO VARIABLE EXPANSION WHEN STRING IS FROM A FILE

$str = implode("",file("foo"));
echo $str;        // prints 'var = "$var" '

// THIS WILL FORCE VARIABLE EXPANSION TO OCCUR:

$str = str_replace('"','\"',$str);  // escape double quotes
echo eval('echo "'.$str.'";');      // prints 'var = "5" '
$str = 'ob_start(); echo "'.$str.'"; ob_get_contents();';
$str = eval($str);
echo $str;                          // prints 'var = "5" '
nutbar at innocent dot com
08-Jun-2005 09:10
A correction to skippy's comment:

"...you can use either ${ or {$ to open the curly expression ie. "${var}" and "{$var}" are equivalent."

Is incorrect.

For simple variables, such as in the example quoted yes both function and yeild the expected result.  However, when dealing with array variables like $array['key'], doing "${array['key']}" will yeild errors or unexpected results.  The correct formatting is "{$array['key']}".
lelon at lelon dot net
27-Oct-2004 12:01
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;
   }
}
$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.
bishop
09-Sep-2004 03:47
Re: Jonathan Lozinski's note on vim syntax highlighting, we use EOHTML, EOSQL, and EOJAVASCRIPT quite frequently for HTML, SQL, and JavaScript, respectively.

eg:

<?php
$query
=<<<EOSQL
SELECT Foo.a,
       Foo.b,
       Bar.a
  FROM Foo
  LEFT
  JOIN Bar
     ON Foo.x=Bar.y
 WHERE Foo.b LIKE '%123%'
EOSQL;
?>

will be highlighted correctly for SQL under VIM.
Jonathan Lozinski
06-Aug-2004 12:03
A note on the heredoc stuff.

If you're editing with VI/VIM and possible other syntax highlighting editors, then using certain words is the way forward.  if you use <<<HTML for example, then the text will be hightlighted for HTML!!

I just found this out and used sed to alter all EOF to HTML.

JAVASCRIPT also works, and possibly others.  The only thing about <<<JAVASCRIPT is that you can't add the <script> tags..,  so use HTML instead, which will correctly highlight all JavaScript too..  There might be one for Text/css too?
skippy zuavra net
20-Jul-2004 08:55
The short version for the curly syntax:

1. $str{something} is the equivalent of $str[something]

2. Inside "" strings you can use any variable, no matter how complex the addressing mode (multiple index array, imbricated objects) by enclosing the variable in {}: "foo{$any_variable}bar".

To add to the confusion:

a) The two uses above have nothing in common, conceptually. For instance, #1 can use operations or functions as that something, #2 is restricted to just variables.

b) In #2, you can use either ${ or {$ to open the curly expression ie. "${var}" and "{$var}" are equivalent.
rtb27 at cam dot ac dot uk
30-Jun-2004 07:59
If you want side effects to occur during variable substituion inside strings, the "?" operator can help. For example:

<?php

$i
= 0;
echo <<<LONGSTRING

one
{${$i++ ? "i" : "i"}}
two
{${$i++ ? "i" : "i"}}
three
{${$i++ ? "i" : "i"}}

LONGSTRING;

?>

will print: "one 1 two 2 three 3"
www.feisar.de
28-Apr-2004 07:49
watch out when comparing strings that are numbers. this example:

<?php

$x1
= '111111111111111111';
$x2 = '111111111111111112';

echo (
$x1 == $x2) ? "true\n" : "false\n";

?>

will output "true", although the strings are different. With large integer-strings, it seems that PHP compares only the integer values, not the strings. Even strval() will not work here.

To be on the safe side, use:

$x1 === $x2
atnak at chejz dot com
11-Apr-2004 03:53
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

Even though it seems like a not-NULL value of type string, it is still considered unset.
zefram at cesena dot net
30-Mar-2004 04:04
Make attention to string conversion!
Strings may evaluate to true but also to zero!!

<?
 $hello
='hi there';
 echo(
$hello?'true':'false');        //true
 
echo($hello==0?'true':'false');      //true!!!!!
 
echo($hello===0?'true':'false');    //false
?>
maka3d at yahoo dot com dot br
26-Feb-2004 10:46
Remember that even PHP is type less, some convertions like INTEGER to STRING is not done when using character direct access like string functions does.
<?php
$str
= '456';
echo
strlen($str); // strlen convert int to string automatically
echo $str{0}; // this works
$str = 456;
echo
$str{0}; // this NOT works
$str = (string)$str; // do type cast to string
echo $str{1}; // now it works
?>
gijs at dghostingworld dot com
23-Feb-2004 11:18
If you use the heredoc syntax and you want to insert an function that echo's something use the following escape sequence: {${header('This is text', 'color')}}

This will execute the function.

hope this helps somebody.

G
marcus at synchromedia dot co dot uk
25-Jan-2004 03:41
If you need to output a string that contains the 'end of php' sequence ?>, or perhaps you have trouble with your editor's syntax colouring because of it, for instance if you wish to do this:

<?php
print "<?xml version=\"1.0\"?>\n";
?>

you can instead use an encoded char to remove the confusion:

<?php
print "<?xml version=\"1.0\"\x3F>\n";
?>

Note that this notes page doesn't have a problem with this syntax!
dandrake
19-Jan-2004 03:41
By the way, the example with the "\n" sequence will insert a new line in the html code, while the output will be decided by the HTML syntax. That's why, if you use

<?
 
echo "Hello \n World";
?>

the browser will receive the HTML code on 2 lines
but his output on the page will be shown on one line only.
To diplay on 2 lines simply use:

<?
 
echo "Hello <br>World";
?>

like in HTML.
mina86 at tlen dot pl
25-Dec-2003 11:00
Re: reuterpl at wp dot pl
No, that's not true.. I mean not exactly true gowever I know what you meant but begginers may not know and feal confused..

<?php
$str
= "Hello \n World";

echo(
$str);
// Output:
//  Hello
//    World
// Browser renders it as:
//  Hello World

echo('<pre>' . $str . '</pre>');
// Output:
//  <pre>Hello
//    World</pre>
// Browser renders it as:
//  Hello
//  World

$str = nl2br($str);
echo(
$str);
// Output:
//  Hello <br /> World
// Browser renders it as:
//  Hello
//  World

echo('<pre>' . $str . '</pre>');
// Output:
//  <pre>Hello <br /> World</pre>
// Browser renders it as:
//  Hello
//
//    World
?>

Re: cs_1 at gmx dot de
I use only UNIX line ends an have no problems with heredoc syntax, so maybe your problem was with something else..
dev6 at es11 dot com
28-Aug-2003 12:42
In response to the most recent post, by Edwin:  Huh? 

First, $foo is not NULL terminated, it's newline terminated.  NULL and \n are not even remotely the same thing. 

Second, the example you posted works perfectly.  Both values get computed and printed as 3.0, not 2.0.
edwin at se-technology dot com
06-Jun-2003 02:58
This one took me a while to sort out:

$foo = "1.5\n";
$bar = "1.5";
printf ("%6.2f, %6.2f ", $foo*2, $bar*2);

>> 2.0, 3.0

So apparently string conversion is messed up by NULL, an obvious solution in case you happen to have a NULL terminated string is:

$foo = rtrim ($foo);
gmarik at hotbox dot ru
24-Apr-2003 11:57
This is how I did it, if tou need to cut big text blocks in easy to browse text blocks:

$str = "bla bla nla. asdfasd. fdsfd fafsasf. asasdwe fdscz asdvc. afasffas. afafs vcxrqw cvea.";

preg_match_all("/.{1500,}?\./s",$str,$out,PREG_PATTERN_ORDER);
list($out) = $out;

print_r($out);

And this is the dynamic menu to navigate between the blocks:

for ($i=0; $i<count($out); $i++) {
$pgnum = $i+1;
echo "<option value=$pgnum>$pgnum</option>";
}
philip at cornado dot com
11-Apr-2003 05:37
Note that in PHP versions 4.3.0 and 4.3.1, the following provides a bogus E_NOTICE (this is a known bug):

echo "$somearray['bar']";

This is accessing an array inside a string using a quoted key and no {braces}.  Reading the documention shows all the correct ways to do this but the above will output nothing on most systems (most have E_NOTICE off) so users may be confused.  In PHP 4.3.2, the above will again yield a parse error.
03-Mar-2003 10:04
Regarding "String access by character":

Apparently if you edit a specific character in a string, causing the string to be non-continuous, blank spaces will be added in the empty spots.

echo '<pre>';
$str = '0123';
echo "$str\n";
$str{4} = '4';
echo "$str\n";
$str{6} = '6';
echo "$str\n";

This will output:
0123
01234
01234 6
Notice the blank space where 5 should be.

(PHP 4.3.1)
cs_1 at gmx dot de
11-Feb-2003 12:57
Be sure to save your PHP files with CrLf line ends when using the heredoc syntax for a variable, e.g.:

$var1 = <<<EOT
sdsdsd
EOT;

didn't work on my linux system when using unix line ends...
Jeff at jsgennusa at yahoo dot com
24-Jan-2003 11:28
This is why this is right:

$beer = 'Heineken';
echo "$beer's taste is great"; // works, "'" is an invalid character for varnames
echo "He drank some $beers";  // won't work, 's' is a valid character for varnames
echo "He drank some ${beer}s"; // works

In all these examples, the php code is looking for the variable $beer. 
In the first one, it works because when it finds $beer's it actually finds $beer and stops at the '. 
In the second one, it doesn't work because there is no variable designated as $beers.
The third one works because the php code reads { and } as specifying what the actually variable is that it should be looking for.  The { and } allow you to add onto the variable.
jm at roth dot lu
18-Jan-2003 07:09
ERRATA?

Shouldn't this :

echo "$beer's taste is great"; // works, "'" is an invalid character for varnames
echo "He drank some $beers";  // , 's' is a valid character for varnames
echo "He drank some ${beer}s"; // works

be like that:

echo "$beer's taste is great"; // won't work, "'" is an invalid character for varnames
echo "He drank some $beers";  // works, 's' is a valid character for varnames
echo "He drank some ${beer}s"; // works
vallo at cs dot helsinki dot fi
03-Nov-2002 05:41
Even if the correct way to handle variables is determined from the context, some things just doesn't work without doing some preparation.

I spent several hours figuring out why I couldn't index a character out of a string after doing some math with it just before. The reason was that PHP thought the string was an integer!

$reference = $base + $userid;
.. looping commands ..
$chartohandle = $reference{$last_char - $i};

Above doesn't work. Reason: last operation with $reference is to store a product of an addition -> integer variable. $reference .=""; (string catenation) had to be added before I got it to work:

$reference = $base + $userid;
$reference .= "";
.. looping commands ..
$chartohandle = $reference{$last_char - $i};

Et voil! Nice stream of single characters.
junkit at gmx dot net
15-Aug-2002 07:08
If you need to escape "$" to be escaped in the output, you need "\\\\$" - or maybe even more!

$ is a control character in Latex. If you want it to become \$ for further processing through Latex, it seems that there must be 4 (!) backslashes - so that in the end there is one left after processing the string twice. Once through str_replace and once through preg_replace!

Using 4.1.0 on Windows.
guidod at gmx dot de
22-Jul-2002 11:26
PHP's double-quoted strings are inherently ill-featured - they will be a problem especially with computed code like in /e-evals with preg_replace.

bash and perl follow the widely accepted rule that all backslashes will escape the nextfollowing char, and nonalpha-chars will always get printed there as themselves whereas (the unescaped chars might have special meaning in regex). Anyway, it is a great way to just escape all nonalpha chars that you uncertain about whether they have special meaning in some places, and ye'll be sure they will get printed literal.

Furthermore, note that \{ sequence is not mentioned in the  escape-char table! You'll get to know about it only "complex (curly) syntax". This can even more be a problem with evals, as they behave rather flaky like it _cannot_ be accomodated for computed code. Try all variants of `echo "hello \{\$world}"` removing one or more of the chars in the \{\$ part - have fun!
03-Jun-2002 02:58
//Some more useful examples (and some that are only interesting):
$foo = 1 + "010";
//$foo is 11, not 9 - i.e. PHP doesn't recognize 010 as octal.

$foo = 1 + "0x10";
//$foo is 17 - i.e. PHP DOES recognize 0x10 as hex for 16.

$foo = 1 + "\x10";
$bar = 1 + "\x35"; //0x35 is ASCII for '5'
//$foo is 1, but $bar is 6.

$foo = 1 + "0x\x41\x31"; //0x41 is ASCII 'A'; 0x31 is '1'
//$foo is 162: 1 + 0xA1 = 1 + 161.

/*NOTE: These examples were "discovered" using PHP4, Apache2,
Red Hat 7.2*/
hleu at tomorrow-ag dot de
17-Aug-2001 06:07
see 'String conversion':
'...Otherwise, the value will be 0 (zero).'

now look at this:
<?php  if (0=='yes') echo "no!!!"?>
yes, it really says "no!!!"
...just something to keep in mind...
philip at cornado dot com
10-Aug-2000 01:38
A nice "Introduction to PHP Strings" tutorial:
  http://www.zend.com/zend/tut/using-strings.php
mmeisinger at commdot dot com
01-Feb-2000 03:28
The new line is very similar to VBScript's "vbcrlf". The only place where you will see the new line is in the "Post-Parsed" Code. The '\n' can also be used to format Email's and Text Files that PHP is writting.
So in closing, use '<br>' to create a new line for your HTML Page and use '\n' to format the Code and Text Files

<Числа с плавающей точкойМассивы>
 Last updated: Tue, 15 Nov 2005