Apostrophe in PHP variable breaks code

时间:2017-10-12 10:06:59

标签: php

I have created a PHP variable:

$msg_gifted='<center><h1>It's a gift! </h1>';

If I leave it like this the code is breaking.

When I replace the apostrophe with:

$msg_gifted='<center><h1>It is a gift! </h1>';

everything works fine. Is there a known way to solve this?

2 个答案:

答案 0 :(得分:1)

you can do

$msg_gifted="<center><h1>It's a gift! </h1>";

or

$msg_gifted='<center><h1>It\'s a gift! </h1>';

Updated answer

You can not use the same quote inside the string without escaping the quote. So you either use different quotes surrounding the string or you escape it with \. Simplified your code to show different possibilites which will all have the same output.

String in single ' quotes

$msg = '<h1>It\'s a gift!</h1><img src="http://path-to-image.jpg" />';

which is almost the same as tring in double " quotes

$msg = "<h1>It's a gift!</h1><img src=\"http://path-to-image.jpg\" />";

Or string concatenation with different quotes just as you prefer:

$msg = "<h1>It's a gift!</h1>";
$msg.= '<img src="http://path-to-image.jpg" />';

答案 1 :(得分:0)

Put \ like this way:

$msg_gifted='<center><h1>It\'s a gift! </h1>';

This is called escaping ' in string in php.