PHP / CHAPTER 02
String offsets and exact parsing
IntermediateDistinguish absent matches, zero offsets, and encoded bytes.
By the end of this chapter
- Check strpos with strict comparison
- State byte-oriented assumptions
- Validate complete input before conversion
The idea
Many core PHP string functions operate on bytes. strlen reports a byte length, and substr uses byte offsets, so arbitrary UTF-8 text requires a deliberate Unicode-aware policy when the requirement concerns characters. For an ASCII protocol, explicitly restrict the accepted alphabet before relying on one byte per character. Do not infer character count from storage size for general user-facing text.
strpos returns either a numeric position or false. Position zero is a successful match at the beginning, so a loose false comparison loses valid results. Use === false to identify absence and !== false to identify success. Conversion is another boundary: casting malformed text to an integer can hide errors, so validate the required complete syntax and range before treating the value as accepted input.
<?php
$text="key:value";
$at=strpos($text, "key");
echo ($at !== false ? "found" : "missing"), "\n";
echo substr($text,0,3), "\n";found key
The successful match is at position zero, which a strict false comparison preserves.
Try it yourself
Return the prefix before a colon or null when the delimiter is absent, including a colon at position zero.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING