Library contents

PHP strlen before substr

substr can return a partial prefix at the end of a short string. Check the size of the label before accepting it.

A simple example

strlen before substr

  1. Start with Text "A"
  2. Do this Request a two-character prefix
  3. Result Too short
Only one character is available. Check the length before extracting two.

Syntax

PHP syntax
strlen($code) >= 3
Run these examples in PHP

Save one example at a time as lesson.php. Use PHP 8.2 or later.

php lesson.php

Read the depot prefix on a damaged label

A parcel scanner expects a three-character depot prefix. A torn label supplies only two characters, so the parcel should go to manual sorting before the software extracts the prefix.

From the program$code = 'NE'
ResultSend to manual sorting
lesson.php
<?php
$code = 'NE';
echo strlen($code) >= 3 ? substr($code, 0, 3) : 'Send to manual sorting';
Output
Send to manual sorting

Two letters cannot identify the three-letter depot. The code routes the parcel to a clerk.

Advertisements

Read a complete lab identifier

A student scans a box showing the code BIO7. Extract the three-character prefix. A short scan must be repeated before the record is filed.

GivenBIO7 · take 3
Worked resultPrefix available

Identify an incomplete scan

A label is folded under the scanner and only two letters reach the form. Extract the three-character prefix. A short scan must be repeated before the record is filed.

GivenAR · take 3
Worked resultRescan

What to watch for

strlen counts bytes. This rule is valid for these ASCII depot identifiers.

Documentation for strlen before substr