Laravel Tutorials

Replace String Prefixes Precisely with Laravel's replaceStart Method

Published
Replace String Prefixes Precisely with Laravel's replaceStart Method image

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.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article