Back to Course |
PHP for Laravel Developers

Popular String Functions: Open-Source Examples

There are many functions for working with strings. Let's check some of them and how they are used in Laravel open-source projects.


str_replace()

class HomeController extends Controller
{
// ...
 
public function pastebin(string $paste = ''): RedirectResponse
{
$paste = str_replace(PHP_EOL, '', $paste);
 
return redirect()->away("https://paste.laravel.io/$paste");
}
}

Link to the example in GitHub repository.


explode()

The explode function is one of the most popular functions. This function returns an array of strings by separating a string with a provided separator.

An example is from an open-source Laravel package spatie/laravel-permission. When creating a new role, the user can provide permissions like so:

php artisan permission:create-role writer web "create articles|edit articles"

After using the explode function, we will get the result:

array:2 [
0 => "create articles"
1 => "edit articles"
]
class CreateRole extends Command
{
// ...
 
protected function makePermissions($string = null)
{
if (empty($string)) {
return;
}
 
$permissionClass = app(PermissionContract::class);
 
$permissions = explode('|', $string);
 
$models = [];
 
foreach ($permissions as $permission) {
$models[] = $permissionClass::findOrCreate(trim($permission), $this->argument('guard'));
}
 
return collect($models);
}
}

Link to the example in GitHub repository.


str_contains()

We can easily check if the string contains some word or symbol using the str_contain function.

An example is from an open-source project Pterodactyl. If the string contains the @ symbol, the if statement returns email.

abstract class AbstractLoginController extends Controller
{
// ...
 
protected function getField(string $input = null): string
{
return ($input && str_contains($input, '@')) ? 'email' : 'username';
}
 
// ...
}

Link to the example in GitHub repository.


sprintf()

A handy string function is the sprintf to format strings.

An example is from an open-source page spatie.be. In the example, for the message, the member's name and age are inserted using the sprintf command. The %s and %dth are called specifiers in the string. Available specifies you can check in the official PHP documentation.

class WishHappyBirthdayCommand extends Command
{
protected $signature = 'spatie:happy-birthday';
 
protected int $ageFilter = 39;
 
protected string $message = 'Congratulations %s on your %dth birthday! 🥳';
 
protected string $filteredMessage = 'Congratulations %s! 🥳';
 
// ...
 
private function sendWishesTo(Member $member): void
{
$message = $this->ageFilter < $member->birthday?->age ? $this->filteredMessage : $this->message;
$message = sprintf($message, $member->name(), $member->birthday?->age);
 
SlackAlert::message($message);
 
$this->info($message);
}
}

Link to the example in GitHub repository.


trim() and strtolower()

Sometimes, users make unintentional spaces, especially at the end of the sentence. The trim function can be used to remove such spaces from the beginning and end of a string. Another great function is to make all letters lowercase in a string.

An example is from an open-source page freek.dev. The string here is made to lowercase, and all whitespaces from the start and end of the string are removed.

class Post extends Model implements Feedable, HasMedia, Sluggable
{
// ...
 
public function updateAttributes(array $attributes)
{
$this->title = $attributes['title'];
$this->text = $attributes['text'];
$this->publish_date = $attributes['publish_date'];
$this->published = $attributes['published'] ?? false;
$this->original_content = $attributes['original_content'] ?? false;
$this->external_url = $attributes['external_url'];
 
$this->save();
 
$tags = explode(',', $attributes['tags_text']);
 
$tags = array_map(fn (string $tag) => trim(strtolower($tag)), $tags);
 
$this->syncTags($tags);
 
return $this;
}
 
// ...
}

Link to the example in GitHub repository.


strtoupper()

The reverse function of strtolower() is the strtoupper(). Using this function, the string is converted to capital letters.

An example is from an open-source page openlittermap-web. Here, the category is converted to capital letters.

class CreateCSVExport implements FromQuery, WithMapping, WithHeadings
{
// ...
 
public function headings (): array
{
$result = [
'id',
'verification',
'phone',
'date_taken',
'date_uploaded',
'lat',
'lon',
'picked up',
'address',
'total_litter',
];
 
foreach (Photo::categories() as $category) {
$result[] = strtoupper($category);
 
$photo = new Photo;
$model = $photo->$category()->make();
$result = array_merge($result, $model->types());
}
 
return array_merge($result, ['custom_tag_1', 'custom_tag_2', 'custom_tag_3']);
}
 
// ...
}

Link to the example in GitHub repository.