paquettg/string-encode
Flexible PHP string encoding helper for multibyte text. Convert strings safely between encodings (UTF-8 by default) with a fluent API, plus utilities for encoding-aware regex handling. Supports PHP 7.2–7.4.
Installation:
composer require paquettg/string-encode
Ensure ext-mbstring is enabled in your php.ini (required by Laravel).
First Use Case: Convert a multibyte string (e.g., user input) to UTF-8 in a Laravel controller:
use StringEncoder\Encoder;
public function processInput(Request $request) {
$encoder = new Encoder();
$cleanText = $encoder->convert()->fromString($request->input('text'))->toString();
// $cleanText is now UTF-8 encoded
}
Where to Look First:
Fluent Conversion Workflow:
// Convert ISO-8859-1 to UTF-8
$encoder->convert()->fromString($str)->toUTF8();
// Validate encoding before conversion
$encoder->validate($str, 'UTF-8');
Laravel Integration:
// app/Providers/AppServiceProvider.php
public function register() {
$this->app->singleton(Encoder::class, function () {
return new Encoder(['defaultEncoding' => 'UTF-8']);
});
}
// app/Facades/StringEncoder.php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class StringEncoder extends Facade {
protected static function getFacadeAccessor() { return 'encoder'; }
}
Usage:
StringEncoder::convert()->fromString($text)->toUTF8();
Validation in Form Requests:
// app/Http/Requests/StorePostRequest.php
use StringEncoder\Encoder;
public function rules() {
return [
'title' => ['required', function ($attribute, $value, $fail) {
$encoder = app(Encoder::class);
if (!$encoder->validate($value, 'UTF-8')) {
$fail('The title must be valid UTF-8.');
}
}],
];
}
Bulk Conversions (e.g., CSV Imports):
$encoder = new Encoder();
$rows = collect($csvData)->map(function ($row) use ($encoder) {
return collect($row)->map(function ($cell) use ($encoder) {
return $encoder->convert()->fromString($cell)->toUTF8();
});
});
Regex with Multibyte Strings:
$encoder = new Encoder();
$pattern = '/[^\p{L}]/u'; // Unicode-aware pattern
$matches = $encoder->regex()->match($pattern, $text);
Data Migration:
DB::table('posts')->update([
'title' => DB::raw('CONVERT(`title` USING utf8mb4)'),
]);
$encoder->validate($title, 'UTF-8') || throw new \Exception('Invalid encoding');
User-Generated Content:
$cleanName = $encoder->convert()->fromString($request->file('avatar')->getClientOriginalName())->toAscii();
Localization:
$translated = trans('messages.welcome');
$encoder->validate($translated, 'UTF-8') || Log::error('Translation encoding issue');
Str Helper:
Combine with Str::of() for hybrid operations:
$cleanText = Str::of($text)->replaceMatches('/[^\p{L}]/u', '')
->toString();
utf8mb4 in migrations for full Unicode support:
Schema::create('posts', function (Blueprint $table) {
$table->string('title')->collation('utf8mb4_unicode_ci');
});
Encoder in unit tests:
$this->partialMock(Encoder::class, ['validate']);
$encoder->shouldReceive('validate')->once()->andReturn(true);
BOM Handling:
removeBOM option may strip unexpected bytes (e.g., in uploaded files). Test with:
$encoder = new Encoder(['removeBOM' => true]);
Encoding Detection:
mb_detect_encoding() is unreliable for mixed-encoding strings. Use mb_check_encoding() for validation:
if (!mb_check_encoding($str, 'UTF-8')) {
throw new \InvalidArgumentException('Invalid UTF-8 string');
}
Regex Performance:
mb_regex is slower than PCRE. Benchmark in high-traffic routes:
// Avoid in loops
$encoder->regex()->match('/pattern/u', $text);
PHP 8.0+ Compatibility:
mb_* functions.Encode class (removed in v2.0.0).File I/O:
toFile()) may overwrite existing files. Use unique filenames:
$encoder->convert()->fromString($text)->toFile(storage_path('app/encoded_'.uniqid().'.txt'));
Invalid Encodings:
mb_convert_encoding() warnings. Use mb_internal_encoding() to debug:
mb_internal_encoding('UTF-8');
$detected = mb_detect_encoding($str);
Facade Issues:
Encoder is registered in the service container:
php artisan vendor:publish --provider="StringEncoder\EncoderServiceProvider"
app(Encoder::class) directly if the facade fails.Regex Failures:
preg_last_error() or mb_regex_encoding():
mb_regex_encoding('UTF-8');
$matches = mb_ereg_match('/pattern/u', $text);
Default Encoding:
$this->app->singleton(Encoder::class, function () {
return new Encoder(['defaultEncoding' => 'Windows-1252']);
});
Case-Sensitive Validation:
$encoder = new Encoder(['caseSensitive' => true]);
$encoder->validate($str, 'UTF-8');
Proxy Support:
$result = \StringEncoder\Encoder::convert()->fromString($str)->toUTF8();
Custom Encoders:
Encoder class for domain-specific logic:
class CustomEncoder extends Encoder {
public function toAscii() {
return $this->convert()->toString('ASCII', 'UTF-8');
}
}
Laravel Events:
// app/Models/Post.php
protected static function booted() {
static::saving(function ($post) {
$encoder = app(Encoder::class);
if (!$encoder->validate($post->title, 'UTF-8')) {
throw new \Exception('Title must be UTF-8 encoded');
}
});
}
Middleware:
// app/Http/Middleware/EncodeRequest.php
public function handle($request, Closure $next) {
$encoder = app(Encoder::class);
foreach ($request->all() as $key => $value) {
if (!$encoder->validate($value, 'UTF-8')) {
return response('Invalid encoding', 400);
}
}
return $next($request);
}
How can I help you explore Laravel packages today?