Replace String Prefixes Precisely with Laravel's replaceStart Method
Last updated on by Harris Raftopoulos

Laravel introduces the Str::replaceStart method for targeted string modifications, enabling developers to replace text only when it appears at the beginning of a string, providing precise control over prefix manipulation.
The replaceStart method offers conditional replacement based on string prefixes:
use Illuminate\Support\Str; // Successful replacement$replaced = Str::replaceStart('Hello', 'Laravel', 'Hello World');// Result: 'Laravel World' // No replacement (doesn't start with 'World')$replaced = Str::replaceStart('World', 'Laravel', 'Hello World');// Result: 'Hello World'
This method proves particularly valuable in path and URL normalization systems:
class PathNormalizer{ public function standardizeProtocol(string $url, string $protocol = 'https') { // Replace http:// with https:// $url = Str::replaceStart('http://', $protocol . '://', $url); // Add protocol if missing if (!str_starts_with($url, $protocol . '://')) { $url = $protocol . '://' . $url; } return $url; } public function unifySubdomain(string $url, string $targetDomain) { // Replace www with target domain $url = Str::replaceStart('www.', $targetDomain . '.', $url); // Replace staging with target domain $url = Str::replaceStart('staging.', $targetDomain . '.', $url); return $url; } public function normalizeApiPath(string $endpoint) { // Remove leading /api if present return Str::replaceStart('/api', '', $endpoint); }}
The replaceStart method provides precise string manipulation by targeting only prefix content, making it ideal for URL normalization, path cleanup, and data transformation tasks where conditional replacement is essential.