bhylu.com

Advertisements

PHP Strings

A string stores bytes representing text or another encoded value. Quotes determine how PHP reads the literal; they do not establish whether the result is safe in HTML, SQL or another context.

How it works

Single-quoted literals perform very limited escaping and do not interpolate ordinary variables. Double-quoted literals can interpolate variables and interpret sequences such as newline. Concatenation explicitly joins values with a dot. Choose the form that keeps a message easy to read. Building text is not the same as encoding it for a destination; output to a browser needs the appropriate HTML, URL or JSON treatment later.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l strings.php
php strings.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Example

PHP 8.2+ · strings.php

<?php
declare(strict_types=1);

$item = "Spade";
$literal = 'Borrow $item';
$interpolated = "Borrow {$item}";
echo $literal, "\n";
echo $interpolated, "\n";
echo "Return " . $item . " tomorrow", "\n";

Expected result

Borrow $item
Borrow Spade
Return Spade tomorrow

The first message preserves the dollar-sign text. The second substitutes the current item value. The third uses concatenation to make the boundary explicit. None of these three strings is automatically an HTML-safe fragment; the output context still decides how a special character must be represented.

Check the official PHP manual for detailed version and API contracts.