webignition/disallowed-character-terminated-string
Install the Package:
composer require webignition/disallowed-character-terminated-string
Basic Usage:
Import the TerminatedString class and instantiate it with a string and terminator characters:
use webignition\DisallowedCharacterTerminatedString\TerminatedString;
$string = new TerminatedString("value #comment", ['#']);
$result = $string->get(); // Returns "value "
First Use Case:
$query = "UPDATE users SET name = 'John' # Old value";
$cleanQuery = (new TerminatedString($query, ['#']))->get();
$logLine = "Error: File not found 2023-10-01 12:00:00";
$logMessage = (new TerminatedString($logLine, [' ']))->get(); // Truncate at last space
Where to Look Next:
TerminatedString::get() and constructor parameters./tests/ for edge cases (e.g., empty strings, no terminators).String Truncation:
get() to retrieve the truncated string.$terminated = new TerminatedString($input, [';', '#']);
$output = $terminated->get();
Laravel Helper Integration:
Create a reusable helper method in app/Helpers/StringHelper.php:
if (!function_exists('terminated_string')) {
function terminated_string(string $string, array $terminators): string {
return (new TerminatedString($string, $terminators))->get();
}
}
Use it in controllers/validators:
$cleanInput = terminated_string($request->input, ['#', '--']);
Validation Rule: Extend Laravel’s validation to enforce string termination:
use Illuminate\Validation\Rule;
Rule::make(function ($attribute, $value, $terminators) {
$terminated = new TerminatedString($value, $terminators);
return strlen($terminated->get()) <= $this->maxLength;
})->terminators(['#', '--']);
Usage in Form Request:
$this->rules = [
'query' => ['required', Rule::terminators(['#'])->max(100)],
];
Service Integration: Register the class in Laravel’s service container for dependency injection:
$this->app->bind(TerminatedString::class, function () {
return new TerminatedString($this->input, $this->terminators);
});
Inject into a service:
public function __construct(private TerminatedString $terminatedString) {}
Dynamic Terminators: Fetch terminators from config or environment:
$terminators = config('app.string_terminators');
$string = new TerminatedString($input, $terminators);
Batch Processing: Process arrays of strings (e.g., log files, CSV rows):
$logLines = file('app.log');
$cleanLines = array_map(
fn($line) => (new TerminatedString($line, ["\n", ' ']))->get(),
$logLines
);
Custom Logic Extension: Extend the class for additional functionality (e.g., trimming whitespace):
class ExtendedTerminatedString extends TerminatedString {
public function getTrimmed(): string {
return trim(parent::get());
}
}
No Terminator Found:
$result = $string->get();
if ($result === $input) {
// No terminator found; handle accordingly
}
Multi-byte Characters:
\u2028) correctly. Test with non-ASCII input:
$string = new TerminatedString("text\u2028hidden", ['\u2028']);
// May not work as expected; use `mb_*` functions if needed.
PHP 8.x Compatibility:
create_function).Performance with Large Strings:
substr() or preg_split():
$nativeResult = substr($input, 0, strpos($input, $terminator));
Case Sensitivity:
array_map('strtolower', $terminators) if case-insensitive matching is needed.Verify Terminators:
// Wrong: new TerminatedString($input, '#')
// Right: new TerminatedString($input, ['#'])
Check for Hidden Characters:
var_export() to inspect strings for invisible terminators:
var_export($input); // Reveals \n, \r, etc.
Edge Cases:
Logging:
Log::debug('Input', ['string' => $input, 'terminators' => $terminators]);
Log::debug('Output', ['result' => $result]);
Composer Lock:
"require": {
"webignition/disallowed-character-terminated-string": "1.0.0"
}
Autoloading:
composer.json:
"autoload": {
"psr-4": {
"webignition\\DisallowedCharacterTerminatedString\\": "vendor/webignition/disallowed-character-terminated-string/src/"
}
}
Custom Terminator Logic:
get() method to add pre/post-processing:
class CustomTerminatedString extends TerminatedString {
public function get(): string {
$result = parent::get();
return str_replace([' ', "\t"], '', $result); // Remove whitespace
}
}
Laravel Facade:
// app/Providers/AppServiceProvider.php
use Illuminate\Support\Facades\Facade;
Facade::register('TerminatedString', function () {
return new \webignition\DisallowedCharacterTerminatedString\TerminatedString(...);
});
Usage:
$result = TerminatedString::make($input, ['#'])->get();
Integration with Laravel Collectives:
laravelcollective/html for HTML comment stripping:
use Collective\Html\HtmlBuilder;
$cleanHtml = HtmlBuilder::stripTags(
(new TerminatedString($dirtyHtml, ['<!--', '-->']))->get()
);
Artisan Commands:
$this->info((new TerminatedString($this->argument('input'), ['#']))->get());
Blade Directives:
Blade::directive('terminate', function ($expression) {
return "<?php echo (new \\webignition\\DisallowedCharacterTerminatedString\\TerminatedString({$expression[0]}, {$expression[1]}))->get(); ?>";
});
Usage in Blade:
@terminate($string, ['#'])
Event Listeners:
public function handle(ContentCreated $event) {
$event->content = (new TerminatedString($event->content,
How can I help you explore Laravel packages today?