Search⌘ K
AI Features

Introduction to Lines and Words

Explore how to manage various line-ending characters like line feed and carriage return in Laravel. Learn to split strings into lines using regular expressions and create helper methods to normalize line endings for consistent string manipulation.

In this chapter, we will explore the concepts of lines and words. Both terms are ubiquitous: we see them everywhere but probably don’t give them much thought. We will start with lines.

PHP
<?php
use Illuminate\Support\Str;
Str::macro('lineSplit', function ($value) {
return explode("\n", $value);
});

When we did this in the previous chapter, we noted that this implementation had some issues. Namely, it does not handle the line-ending types we often encounter. Our current line-splitting implementation only accounts for the \n (line feed) character, which will work well with text input or documents from UNIX or modern macOS systems. However, there are others.

For example, older macOS systems would use the \r (carriage return), and Windows systems use the \r\n sequence (carriage return followed by a line feed). These characters are interesting in their own right. Most developers will have interacted with completely digital systems and might not know that each of these characters has ...