String Cleaning with Laravel's remove Method
Need to remove certain characters from your strings? Laravel's Str::remove method provides a straightforward way to clean up text content.
Basic Usage
Remove specific characters from a string:
use Illuminate\Support\Str;
$string = 'Peter Piper picked a peck of pickled peppers.';
$removed = Str::remove('e', $string);
// Result: "Ptr Pipr pickd a pck of pickld ppprs."
// Case-insensitive removal
$removed = Str::remove('P', $string, false);
// Result: "eter ier icked a eck of ickled eers."
Real-World Example
Here's how you might use it in a text processing service:
class TextCleaner
{
public function cleanupPhoneNumber(string $phone)
{
return Str::remove(['-', ' ', '(', ')'], $phone);
}
public function removeSpecialCharacters(string $text)
{
$characters = ['@', '#', '$', '%', '^', '&', '*'];
return Str::remove($characters, $text);
}
public function sanitizeUsername(string $username)
{
// Remove common special characters and spaces
$cleaned = Str::remove([
' ', '.', '-', '_', '@',
], $username);
return strtolower($cleaned);
}
public function cleanupCSVContent(string $content)
{
// Remove invisible characters
return Str::remove([
"\r", "\n", "\t", "\0", "\x0B"
], $content);
}
}
// Usage
class UserController extends Controller
{
public function store(Request $request, TextCleaner $cleaner)
{
$phone = $cleaner->cleanupPhoneNumber($request->phone);
$username = $cleaner->sanitizeUsername($request->username);
User::create([
'phone' => $phone,
'username' => $username
]);
}
}
The remove method simplifies string cleaning operations, making your text processing code more readable and maintainable.
If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter and Bluesky. It helps a lot!