string++php,String 字符串

用户评论:

[#1]

cnbk201 at gmail dot com [2015-01-12 22:07:20]

Small note to consider in heredoc multiple dimension array will not work and neither will any native language functions

$a[1] ="man";$b['man'] ="player";

echo <<

substr($a[1], 1) // will result in substr(man, 1)

ED;

?>

[#2]

Anonymous [2014-03-31 15:33:45]

$my_int = "12,140";

echo  1 + $my_int ;

Returns 13 not the expected 12141

[#3]

Ray.Paseur often uses Gmail [2014-03-08 13:14:16]

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.

[#4]

benl39 at free dot fr [2014-03-04 09:14:24]

Note that :

<?phpecho 'error'==0,'
';// TRUEecho'error'=='0','
';// FALSEecho'0'==0,'
';// TRUE

// So, 'error' != 'error' ??>

[#5]

necrodust44 at gmail dot com [2014-03-04 01:52:28]

String conversion to numbers.

Unfortunately, the documentation is not correct.

?The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).?

It is not said and is not shown in examples throughout the documentation that, while converting strings to numbers, leading space characters are ignored, like with the strtod function.

However, PHP's behaviour differs even from the strtod's. The documentation says that if the string contains a "e" or "E" character, it will be parsed as a float, and suggests to see the manual for strtod for more information. The manual says

?A hexadecimal number consists of a "0x" or "0X" followed by a nonempty sequence of hexadecimal digits possibly containing a radix character, optionally followed by a binary exponent.  A binary exponent consists of a 'P' or 'p', followed by an optional plus or minus sign, followed by a nonempty sequence of decimal digits, and indicates multiplication by a power of 2.?

But it seems that PHP does not recognise the exponent or the radix character.

strtod also uses the current locale to choose the radix character, but PHP ignores the locale, and the radix character is always 2E. However, PHP uses the locale while converting numbers to strings.

With strtod, the current locale is also used to choose the space characters, I don't know about PHP.

[#6]

espertalhao04 at hotmail dot com [2013-12-10 10:34:09]

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.

If you read carefully, you will notice this, in the 1st sentence of the warning about heredocs:

"It is very important to note that the line with the closing identifier must contain no other characters, except a semicolon (;)."

Interesting...

It is refering about semicolons...

But wait, there is more:

http://php.net/manual/en/language.basic-syntax.instruction-separation.php

1st sentence says:

"As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement."

So, here says that semicolons are statement separators, basicly...

So, if you put a "real" semicolon at the end of these examples:

$a=5;$foo="String";$bar=array();$yep=null;$other=func();?>

Why shouldn't you put at the end of heredocs and nowdocs?

After all, a heredoc or a nowdoc is simply a string.

You should read more carefully the documentation first before saying any comment.

About serious questions:

I didn't read all comments here, but you can run functions inside strings and heredocs.

And you can even nest them inside {}

Example:

$f=function($x){$a=func_get_args();unset($a[0]);returncall_user_func_array($x,$a);};$d=0;

echo$b=<<

,"Example",<<

)}NUMBERS;?>

It's not pretty, and is hard to read, but sometimes it is useful to confuse curious people (like minifying the code).

Warning: if any function that runs inside a string or heredoc gives a fatal error, the script MAY continue!

[#7]

php at richardneill dot org [2013-02-28 18:20:54]

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().

[#8]

mcamiano at ncsu dot edu [2012-10-05 14:43:54]

Regarding the lack of complex expression interpolation, just assign an identity function to a variable and call it:

function id($arg) { return $arg; }

$expr = id;

echo "Field is: {$expr( "1 ". ucfirst('whatzit')) }";

It is slower due to an additional function call, but it does avoid the assignment of a one-shot temporary variable. When there are a lot of very simple value transformations made just for display purposes, it can de-clutter code.

[#9]

Denis R. [2012-06-10 11:01:54]

Hi.

I noticed that the documentation does not mention that when you have an XML element which contains a dash (-) in its name can only be accessed using the bracelets notation.

For example:

value4element-one

to access the above 'element-one' using SimpleXML you need to use the following:

$simpleXMLObj->root->{'element-one'}

to retrieve the value.

Hope this helps,

Denis R.

[#10]

m021 at springtimesoftware dot com [2012-04-01 14:00:09]

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.

[#11]

gtisza at gmail dot com [2012-01-10 06:32:10]

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.

This works:

$foo= <<

This does not:

foo(<<

);// syntax error, unexpected ';'?>

Without semicolon, it works fine:

foo(<<

);?>

[#12]

sgbeal at googlemail dot com [2011-08-12 04:44:13]

The docs say: "Heredoc text behaves just like a double-quoted string, without the double quotes" but there is a notable hidden exception to that rule: the final newline in the string (the one before closing heredoc token) is elided. i.e. if you have:

$foo = <<

a

b

c

EOF;

the result is equivalent to "a\nb\nc", NOT "a\nb\nc\n" like the docs imply.

[#13]

Michael [2011-05-09 05:56:29]

Just want to mention that if you want a literal { around a variable within a string, for example if you want your output to be something like the following:

{hello, world}

and all that you put inside the {} is a variable, you can do a double {{}}, like this:

$test = 'hello, world';

echo "{{$test}}";

[#14]

Ultimater at gmail dot com [2011-04-27 15:18:51]

If you require a NowDoc but don't have support for them on your server -- since your PHP version is less than PHP 5.3.0 -- and you are in need of a workaround, I'd suggest using PHP's __halt_compiler() which is basically a knock-off of Perl's __DATA__ token if you are familiar with it.

Give this a run to see my suggestion in action:

echo <<

NowDoc support for PHP < 5.3.0

content="Note that I built this code explicitly for the

php.net documenation for demonstrative purposes." />

body{text-align:center;}

table.border{background:#e0eaee;margin:1px auto;padding:1px;}

table.border td{padding:5px;border:1px solid #8880ff;text-align:left;

background-color:#eee;}

code ::selection{background:#5f5color:white;}

code ::-moz-selection{background:#5f5;color:white;}

a{color:#33a;text-decoration:none;}

a:hover{color:rgb(3,128,252);}

href="http://php.net/manual/en/language.types.string.php#example-77">

Example #8 Simple syntax example

$nowDoc
EOF;

__halt_compiler()//Example code snippet we want displayed on the webpage

//note that the compiler isn't actually stopped until the semicolon;<?php

$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 juice made of$juice[0]s.".PHP_EOL;// Won't workecho"He drank some$juices[koolaid1]juice.".PHP_EOL;

classpeople{

public$john="John Smith";

public$jane="Jane Smith";

public$robert="Robert Paulsen";

public$smith="Smith";

}$people= newpeople();

echo"$people->johndrank some$juices[0]juice.".PHP_EOL;

echo"$people->johnthen said hello to$people->jane.".PHP_EOL;

echo"$people->john's wife greeted$people->robert.".PHP_EOL;

echo"$people->robertgreeted the two$people->smiths.";// Won't work?>

[#15]

dee jay simple 0 0 7 at ge mahl dot com [2011-03-01 12:15:57]

I recently discovered the joys of using heredoc with sprintf and positions. Useful if you want some code to iterate, you can repeat placeholders.

return ($foo+$num);

}

functiongetString() {$foo= array("California","Oregon","Washington");shuffle($foo);

return$foo[0];

}

functiongetDiv() {$num=getNumber();$div=sprintf("

%s
",getNumber(rand(-5,5)) );

return$div;

}$string= <<

I picked: %2\$d as a number, 

I also picked %2\$d as a number again 

%3\$s

%3\$s

%3\$s

%3\$s

%3\$s
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

[#16]

saamde at gmail dot com [2010-05-27 15:40:58]

Watch out for the "unexpected T_SL" error.  This appears to occur when there is white space just after "<<

[#17]

"Sascha Ziemann" [2009-12-17 01:58:54]

Empty strings seem to be no real strings, because they behave different to strings containing data. Here is an example.

It is possible to change a character at a specific position using the square bracket notation:

$str='0';$str[0] ='a';

echo$str."\n";// => 'a'?>

It is also possible to change a character with does not exist, if the index is "behind" the end of the string:

$str='0';$str[1] ='a';

echo$str."\n";// => 0a?>

But if you do that on an empty string, the string gets silently converted into an array:

$str='';$str[0] ='a';

echo$str."\n";// => Array?>

[#18]

shd at earthling dot net [2009-10-20 02:54:24]

If you want a parsed variable surrounded by curly braces, just double the curly braces:

$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.

[#19]

deminy at deminy dot net [2009-09-16 21:08:16]

Although current documentation says 'A string literal can be specified in four different ways: ...', actually there is a fifth way to specify a (binary) string:

The above statement declares a binary string using the 'b' prefix, which is available since PHP 5.2.1. However, it will only have effect as of PHP 6.0.0, as noted on http://www.php.net/manual/en/function.is-binary.php .

[#20]

Liesbeth [2009-09-03 01:54:58]

If you need to emulate a nowdoc in PHP 

A text with 'quotes'

and $$$dollars$$$.

<?php  $input=ob_get_contents();ob_end_clean();// Do what you want with $inputecho"

".$input."";?>

[#21]

headden at karelia dot ru [2009-06-20 00:43:20]

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:

functionc($a,$b) { return$a+$b; }// Usageecho"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(...)}?>

[#22]

cvolny at gmail dot com [2008-12-02 23:43:36]

I commented on a php bug feature request for a string expansion function and figured I should post somewhere it might be useful:

using regex, pretty straightforward:

<?phpfunctionstringExpand ($subject, array$vars) {// loop over $vars mapforeach ($varsas$name=>$value) {// use preg_replace to match ${`$name`} or $`$name`$subject=preg_replace(sprintf('/\$\{?%s\}?/',$name),$value,$subject);

}// return variable expanded stringreturn$subject;

}?>

using eval() and not limiting access to only certain variables (entire current symbol table including [super]globals):

else$delim='__ASDFZXCV1324ZXCV__';// button mashing...

// built the eval code$statement="return <<

throw newEvalException($statement);// return variable expanded stringreturn$result;

}?>

I hope that helps someone, but I do caution against using the eval() route even if it is tempting.  I don't know if there's ever a truely safe way to use eval() on the web, I'd rather not use it.

[#23]

Obeliks [2008-11-15 20:21:36]

Expectedly <?php  $string[$x]?> and <?php  substr($string,$x,1)?> will yield the same result... normally!

However, when you turn on the  Function Overloading Feature (http://php.net/manual/en/mbstring.overload.php), this might not be true!

If you use this Overloading Feature with 3rd party software, you should check for usage of the String access operator, otherwise you might be in for some nasty surprises.

[#24]

Salil Kothadia [2008-10-15 01:33:06]

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.

foo1.php code gives "syntax error, unexpected $end".

But in foo2.php and foo3.php, when you add a php close tag or when you have some more code after heredoc it works fine.

Example Code:

foo1.php

1. <?php

2. $str= <<

4. spanning multiple lines

5. using heredoc syntax.

6. EOD;

7.

foo2.php

1. <?php

2.$str= <<

3. Example of string

4. spanning multiple lines

5. using heredoc syntax.

6. EOD;

7.

8. echo$str;

9.

foo3.php

1. <?php

2.$str= <<

3. Example of string

4. spanning multiple lines

5. using heredoc syntax.

6. EOD;

7. ?>

[#25]

steve at mrclay dot org [2008-09-30 13:33:30]

Simple function to create human-readably escaped double-quoted strings for use in source code or when debugging strings with newlines/tabs/etc.

for ($i=0,$l=strlen($str);$i

if ($o<31||$o>126) {

switch ($o) {

case9:$ret.='\t'; break;

case10:$ret.='\n'; break;

case11:$ret.='\v'; break;

case12:$ret.='\f'; break;

case13:$ret.='\r'; break;

default:$ret.='\x'.str_pad(dechex($o),2,'0',STR_PAD_LEFT);

}

} else {

switch ($o) {

case36:$ret.='\$'; break;

case34:$ret.='\"'; break;

case92:$ret.='\\\\'; break;

default:$ret.=$str[$i];

}

}

}

return$ret.'"';

}?>

[#26]

chAlx at findme dot if dot u dot need [2008-09-11 08:42:47]

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)?>

[#27]

harmor [2008-09-01 15:05:20]

So you want to get the last character of a string using "String access and modification by character"?  Well negative indexes are not allowed so $str[-1] will return an empty string.

//Tested using: PHP 5.2.5

$str = 'This is a test.';

$last = $str[-1];                  //string(0) ""

$realLast = $str[strlen($str)-1];  //string(1) "."

$substr = substr($str,-1);         //string(1) "."

echo '

';

var_dump($last);

var_dump($realLast);

var_dump($substr);

[#28]

Evan K [2008-02-28 13:03:15]

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.

returnpreg_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]) );'),$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);?>

[#29]

rkfranklin+php at gmail dot com [2007-09-26 12:35:45]

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:

$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++]}
";// these print Georgeecho"{$myArray['Person'.$i]}
";

echo"{$myArray["Person{$i}"]}
";// These don't workecho"{$myArray['Person$i']}
";

echo"{$myArray['Person'$i]}
";// These both throw fatal errors

// echo "$myArray[Person$i]
";

//echo "$myArray[Person{$i}]
";?>

[#30]

Richard Neill [2007-05-31 20:31:30]

Unlike bash, we can't do

echo "\a"       #beep!

Of course, that would be rather meaningless for PHP/web, but it's useful for PHP-CLI. The solution is simple:  echo "\x07"

[#31]

og at gams dot at [2007-04-25 17:06:09]

easy transparent solution for using constants in the heredoc format:

DEFINE('TEST','TEST STRING');

$const = get_defined_constants();

echo <<

{$const['TEST']}

END;

Result:

TEST STRING

[#32]

penda ekoka [2007-04-24 10:14:28]

error control operator (@) with heredoc syntax:

the error control operator is pretty handy for supressing minimal errors or omissions. For example an email form that request some basic non mandatory information to your users. Some may complete the form, other may not. Lets say you don't want to tweak PHP for error levels and you just wish to create some basic template that will be emailed to the admin with the user information submitted. You manage to collect the user input in an array called $form:

<?php // creating your mailer$mailer= newSomeMailerLib();$mailer->from=' System ';$mailer->to='admin@yourwebsite.com';$mailer->subject='New user request';// you put the error control operator before the heredoc operator to suppress notices and warnings about unset indices like this$mailer->body= @<<

[#33]

bryant at zionprogramming dot com [2007-02-27 12:16:27]

As of (at least) PHP 5.2, you can no longer convert an object to a string unless it has a __toString method. Converting an object without this method now gives the error:

PHP Catchable fatal error:  Object of class  could not be converted to string in  on line 

Try this code to get the same results as before:

} else {$string='Object';

}?>

[#34]

fmouse at fmp dot com [2007-02-21 10:20:46]

It may be obvious to some, but it's convenient to note that variables _will_ be expanded inside of single quotes if these occur inside of a double-quoted string.  This can be handy in constructing exec calls with complex data to be passed to other programs.  e.g.:

$foo = "green";

echo "the grass is $foo";

the grass is green

echo 'the grass is $foo';

the grass is $foo

echo "the grass is '$foo'";

the grass is 'green'

[#35]

bishop [2006-03-28 12:58:56]

You may use heredoc syntax to comment out large blocks of code, as follows:

echo ($test== 'foo' ? 'bar' : 'baz');

echo <<

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.

[#36]

webmaster at rephunter dot net [2005-11-30 08:57:07]

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 = <<

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 = <<

this is a string that must be

followed by a single newline

EOT;

[#37]

DELETETHIS dot php at dfackrell dot mailshell dot com [2005-11-01 08:05:59]

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:

functionb() {

return"World";

}

}$c= newa;

echo"Hello{$c->b()}.\n"?>

While this does not:

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.

[#38]

lelon at lelon dot net [2004-10-27 12:01:45]

You can use the complex syntax to put the value of both object properties AND object methods inside a string.  For example...

public$one=1;

public functiontwo() {

return2;

}

}$test= newTest();

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 '$'.

constONE=1;

}

echo"foo {Test::ONE} bar";?>

This will output "foo {Test::one} bar".  Constants and static properties require you to break up the string.

[#39]

Jonathan Lozinski [2004-08-06 12:03:58]

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 <<

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

JAVASCRIPT also works, and possibly others.  The only thing about << tags..,  so use HTML instead, which will correctly highlight all JavaScript too..

You can also use EOHTML, EOSQL, and EOJAVASCRIPT.

[#40]

www.feisar.de [2004-04-28 07:49:00]

watch out when comparing strings that are numbers. this example:

$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

[#41]

atnak at chejz dot com [2004-04-11 15:53:50]

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值