Strings

PHP String Helper Functions

Reusable helpers for HTML escaping, whitespace normalization and safe excerpts.

Overview

Reusable helpers for HTML escaping, whitespace normalization and safe excerpts.

Code example

<?php
declare(strict_types=1);
function e(string $v): string { return htmlspecialchars($v,ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8'); }
function normalizeWhitespace(string $v): string { return trim((string)preg_replace('/\s+/u',' ',$v)); }
function excerpt(string $v,int $max=120): string { return mb_strlen($v)<=$max?$v:mb_substr($v,0,max(0,$max-1)).'…'; }

How to use it

Place the snippet in a namespaced helper or service file, adapt its inputs to your application and add tests for expected and edge-case behavior.

Notes

The example is intentionally small. Validate untrusted input, handle exceptions and document any PHP extension or database requirements.