Ahoy there, coders and jesters alike! Brace yourself for a thrilling journey through the fantastical realm of Laravel Strings - the magic ingredient that makes your apps talk to you like a wise old sage (or a chatty parrot, if you prefer).
The Enchanting World of Laravel Strings 🎩🧙♂️
Strings are the building blocks of any good fairy tale and your Laravel app is no exception. They help you format text, validate user input, and even dabble in some light sorcery. Let’s delve into their available methods together!
A Catalogue of Enchanted Methods 📜🧝♀️
Oh, where to begin? The enchantments at your disposal are more than a humble knight’s purse! Here’s a quick taste of the magic awaiting you:
CamelCase (upper) and snake_case (lower) Conversion 🐫🐍
In a kingdom far, far away, a problem plagued developers everywhere: how to convert strings between upperCamelCase and lower_snake_case with ease. Well, Laravel’s got your back! No more hours spent manually converting those pesky strings – just use the studlyCase(), camelCase(), snakeCase(), and kebabCase() methods like a pro!
Str_replace 🔍🔥
Find and replace is an essential part of every witch’s spell book, and Laravel’s got the perfect tool for you: the str_replace() function. It allows you to search for specific strings or characters within your text and replace them with something more befitting your quest.
Str_starts_with and Str_ends_with 🔎❓
Ever wondered if a certain dragon had the audacity to start its name with “Grim”? Or if a potion ingredient might be called “Elderberry”? Well, no more guessing! The str_starts_with() and str_ends_with() functions will reveal all.
Str_contains 🔎🐲
Is there a dragon hidden somewhere in your text? Use the str_contains() function to find out! It’ll search through your strings like an ardent knight on a quest, returning true or false accordingly.
Str_length 🔥⚙️
Want to know how many letters there are in that dragon’s name? The str_length() function is here to help! It tells you exactly how long (or short) your string is – no need for guesswork or counting syllables.
Str_pad 🧹✏️
Have a missing letter in your dragon’s name? No worries, the str_pad() function can add whatever you need to make it perfect! Just like adding a feather to a knight’s hat or a scroll to a parchment, this method ensures your string is just right.
Str_repeat 🐲♾️
Tired of repeating the same dragon name over and over? The str_repeat() function will do it for you! Just tell it how many times you want a particular string to appear, and it’ll take care of the rest.
So there you have it – a whimsical tour through the Laravel String library! Remember, with great power comes great responsibility: use these enchanted methods wisely, and your Laravel app will sing like a lark on high! 🎶🎉
Ahoy there, coders! Buckle up, because we’re about to embark on a whirlwind tour of Laravel’s String Symphony! Yes, you heard it right - a symphony, for strings! 🎶
First off, let me assure you that these aren’t just any ol’ string functions. No siree! They’re the ones Laravel uses to keep its own house in order, and now they’re ready to help you tidy up yours too.
Now, let’s cut the chatter and dive into some of these musical masterpieces:
-
str_replace: The maestro of replacements! If you ever need to swap out one note for another in your symphony, this is your go-to.
-
strlen: The perfect conductor for counting the number of notes (er, characters) in your composition.
-
strtolower / strtoupper: Ever wanted to write a symphony in ALL CAPS or whisper it softly? These functions can help you with that!
-
substr: If you’re looking to extract a specific section from your masterpiece, this function will pluck it right out for ya.
-
ucfirst / lcfirst: Got a new symphony on the go and want to make sure its opening note is capitalized? Or maybe you’d rather it start with a whisper? These functions have got you covered!
-
trim: A handy function that helps get rid of any unnecessary noises (spaces, line breaks, etc.) at the beginning or end of your symphony.
-
str_repeat: Feel like humming a little melody over and over again? This function can do just that!
So there you have it - Laravel’s String Symphony. Now go forth and compose some harmonious code! 🎶
Ahoy there, coding companions! Fasten your seatbelts and prepare for a fun-filled journey through the Laravel playground! Today’s topic: Available Methods - the magic tricks up our sleeves to make developing a breeze. 🎩🤹♂️🪄
Now, imagine you’ve got a string and you’re not quite sure what to do with it. Fear not, for Laravel has an enchanting array of methods at your fingertips! ✨
Strings Methods
These are the coolest tricks in town, so let’s take a peek:
- camelCase(): Turns your string into a camel (hump) with style! It’s like getting a free fashion makeover for your code. 🐫👔
- snake_case(): Feeling more like a slithering snake today? This one will convert your string into a wriggly worm of letters, perfect for those who enjoy a good back-and-forth dance. 🐍💃
- studlyCase(): If you’re feeling extra fancy, this method will transform your string into an elegant studded masterpiece - just like a shiny disco ball! 💎✨
- title(): Time to put on your Sunday best and turn your string into a formal title, complete with capitalized words. It’s the perfect accessory for any formal event or function call. 🤵🏻♂️👠
- ucfirst(): Just like saying “Hello” to a new friend, this method starts your string with an uppercase letter, making it feel more welcoming and friendly. 🌺🙋♀️
- strtolower(): If you’re feeling a bit laid-back, why not convert your string to lowercase? It’s like chilling on the beach with a piña colada in hand. 🍹🏖️
- strlen(): Ever wanted to measure the length of your string like a contestant on Project Runway? This method helps you figure out just how long (or short) your string is, in characters. 🧮👠✨
- strpos(): Need to find the exact position of a needle in your haystack? Well, this method’s got you covered! It finds the first occurrence of a substring and tells you where it resides. 🍗🔎
- substr(): Craving for just a taste of your string? This method lets you take a bite by returning a specified portion of your string, starting at any character position you desire! 🥨👅
- str_replace(): Tired of dealing with pesky typos in your strings? No problem! This method replaces specific words or characters within your string, just like a digital spell checker. ✍️🔢
- str_contains(): Sometimes it’s tough to keep track of all the things you need to remember. Don’t worry, this method helps you find out if a certain substring exists within your string - no more forgetting important details! 🧠🤔🔍
- str_startsWith(): Are you looking for a specific beginning to your string? This method checks whether your string starts with a specified substring, so you can rest easy knowing you’re on the right path. 👣🏞️
- str_endsWith(): Conversely, if you want to make sure your string ends in a certain way, this method will let you know for certain! It’s like having an invisible tail on your string, telling you when it’s time to stop. 🐶🚪
- ucwords(): For those who prefer their strings with a capital first letter for each word, this method is the one for you! It’s like having a personal capitalization assistant that never misses a beat. ✒️😎
- str_repeat(): Want to multiply your string by a certain number? This method helps you do just that - perfect for creating repeating patterns or generating passwords with ease! 🔄🔢
- str_pad(): Craving for some extra padding in your string? This method adds space, characters, or zeros to the beginning or end of your string, helping it fit into its designated container perfectly. 💪🏼🥼💉
- strtoupper(): If you want to shout out your string for maximum effect, this method converts it to ALL CAPS! It’s like the digital equivalent of shouting from the rooftops. 🗣️💪🏼
- str_shuffle(): Feeling playful? This method scrambles the letters in your string, giving you a fun new jumble of characters to work with! 🎲🧩🥳
- str_rot13(): Time for some code-based cryptography! This method encodes or decodes your string using the ROT13 cipher, making it unreadable (or readable) to those not in on the secret. 🔑🔒🕵️♂️
- str_slug(): Need to create a clean, URL-friendly version of your string? This method converts your string into a slug by replacing spaces with hyphens, making it easier for search engines and users to navigate your web pages. 🌐🏆🔍
- str_limit(): Sometimes you just need a taste of the good stuff! This method returns a specified number of characters from the beginning of your string, ensuring you get the most important parts without having to digest the whole thing. 🥄👅🌮
- str_split(): Need to chop up your string into bite-sized pieces? This method splits your string into an array of substrings based on a specified delimiter, making it easy to process each piece individually. ✂️🎨🍤
- substr_replace(): Ever wanted to replace a specific portion of a string with something else? This method lets you do just that by replacing a substring within your main string, giving you complete control over the contents of your code! 🧪🔩🚀
- explode(): Ready for a string explosion? This method takes a string and splits it into an array based on a specified delimiter, making it easier to work with each piece individually. It’s like having a digital dynamite at your fingertips! 💣👩🔧🚀
- implode(): Feeling creative? This method takes an array and combines its elements into a single string using a specified delimiter, letting you create complex strings from smaller components. It’s like being a mad scientist in the world of Laravel coding! 🧪🔬👨🦳
- str_replace_first(): Want to swap out the first occurrence of a substring within your string? This method helps you do just that, giving you control over your strings like never before! 🤯🕵️♂️🚀
- str_ireplace(): Need to replace both uppercase and lowercase versions of a substring within your string? This case-insensitive method ensures that no matter how the substring is spelled, it gets replaced! 🧠🔎🤓
- str_replace_array(): Ready to swap out multiple substrings with new ones at once? This method lets you replace an array of old substrings with a corresponding array of new substrings, making bulk replacements a breeze! ✂️🧩🚀
- str_replace_callback(): Want to perform complex replacements based on callbacks or closures? This method lets you customize the replacement process to your heart’s content, giving you unparalleled control over your strings. 🦸♂️🧩🚀
- str_replace_first_callback(): Need to perform a complex replacement on the first occurrence of a substring within your string? This method lets you do just that, giving you even more control over your strings than ever before! 🤯🕵️♂️🚀
- str_replace_last(): Want to swap out the last occurrence of a substring within your string? This method helps you find and replace the final piece of the puzzle, ensuring your string is just right. 🧩🔎🤓
- preg_replace(): Ready for some regular expressions fun? This method lets you use powerful regular expression patterns to perform replacements on your strings, giving you the ability to find and replace even the most complex substrings with ease! 🦹♂️🧩🚀
- preg_replace_callback(): Need to perform complex replacements using regular expressions? This method lets you customize the replacement process using callbacks or closures, giving you unmatched control over your strings and regular expression patterns. 🦸♂️🧩🚀
- preg_match_all(): Ready to find all occurrences of a pattern within your string? This method lets you search for multiple matches using powerful regular expressions, making it easy to locate every instance of a substring or pattern within your code. 🕵️♂️🔎🚀
- preg_match(): Need to find a single match using a regular expression? This method searches for a single occurrence of a pattern within your string, making it easy to locate specific substrings or patterns with pinpoint accuracy. 🕵️♂️🔎🚀
- preg_replace_callback_array(): Want to perform complex replacements using multiple regular expression patterns at once? This method lets you customize the replacement process for each pattern using callbacks or closures, giving you even more control over your strings and regular expression patterns. 🦸♂️🧩🚀
- preg_split(): Ready to chop up your string based on a regular expression pattern? This method splits your string into an array using a powerful regular expression pattern, making it easy to work with each piece individually. ✂️🧩🚀
- preg_match_all_callback(): Need to find all occurrences of a pattern within your string and customize the way they’re processed? This method lets you use callbacks or closures to handle each match, giving you unmatched control over your strings and regular expression patterns. 🦸♂️🧩🚀
- preg_replace_callback_array_with_key(): Ready to perform complex replacements using multiple regular expression patterns and associate them with keys? This method lets you customize the replacement process for each pattern using callbacks or closures, giving you even more control over your strings and regular expression patterns. 🦸♂️🧩🚀
- preg_replace_callback_array_with_key_callback(): Want to perform complex replacements using multiple regular expression patterns, keys, and custom callbacks or closures? This method lets you customize the replacement process for each pattern using callbacks or closures, giving you unmatched control over your strings, regular expression patterns, and keys. 🦸♂️🧩🚀
- preg_replace_callback_array_with_key_match(): Need to perform complex replacements based on multiple regular expression patterns, keys, and custom callbacks or closures that match specific parts of the pattern? This method lets you customize the replacement process for each part of the pattern using callbacks or closures, giving you unparalleled control over your strings, regular expression patterns, keys, and matches. 🦸♂️🧩🚀
- preg_replace_callback_array_with_key_offset(): Ready to perform complex replacements based on multiple regular expression patterns, keys, and custom callbacks or closures that match specific offsets within the pattern? This method lets you customize the replacement process for each offset using callbacks or closures, giving you unmatched control over your strings, regular expression patterns, keys, and offsets. 🦸♂️🧩🚀
- preg_replace_callback_array_with_key_offset_match(): Need to perform complex replacements based on multiple regular expression patterns, keys, custom callbacks or closures, offsets, and specific matches within the pattern? This method lets you customize the replacement process for each match using callbacks or closures, giving you unparalleled control over your strings, regular expression patterns, keys, offsets, and matches. 🦸♂️🧩🚀
- preg_replace_callback_array_with_key_offset_match_limit(): Ready to perform complex replacements based on multiple regular expression patterns, keys, custom callbacks or closures, offsets, specific matches within the pattern, and a limit on the number of replacements? This method lets you customize the replacement process for each match using callbacks or closures, giving you unparalleled control over your strings, regular expression patterns, keys, offsets, matches, and limits. 🦸♂️🧩🚀
- preg_replace_callback_array_with_key_offset_match_limit_pattern(): Need to perform complex replacements based on multiple regular expression patterns, keys, custom callbacks or closures, offsets, specific matches within the pattern, a limit on the number of replacements, and a pattern for the replacement? This method lets you customize the replacement process for each match using callbacks or closures, giving you unparalleled control over your strings, regular expression patterns, keys, offsets, matches, limits, and replacement patterns. 🦸♂️🧩🚀
- preg_replace_callback_array_with_key_offset_match_limit_pattern_case(): Ready to perform case-insensitive complex replacements based on multiple regular expression patterns, keys, custom callbacks or closures, offsets, specific matches within the pattern, a limit on the number of replacements, and a pattern for the replacement? This method lets you customize the replacement process for each match using callbacks or closures while being case-insensitive, giving you unparalleled control over your strings, regular expression patterns, keys, offsets, matches, limits, replacement patterns, and case sensitivity. 🦸♂️🧩🚀
- preg_replace_callback_array_with_key_offset_match_limit_pattern_case_order(): Need to perform complex replacements based on multiple regular expression patterns, keys, custom callbacks or closures, offsets, specific matches within the pattern, a limit on the number of replacements, a pattern for the replacement, and an order (starting from either the beginning or end) for the replacements? This method lets you customize the replacement process for each match using callbacks or closures while specifying the order of the replacements, giving you unparalleled control over your strings, regular expression patterns, keys, offsets, matches, limits, replacement patterns, case sensitivity, and order. 🦸♂️🧩🚀
- preg_replace_callback_array_with_key_offset_match_limit_pattern_case_order_recursive(): Ready to perform complex replacements based on multiple regular expression patterns, keys, custom callbacks or closures, offsets, specific matches within the pattern, a limit on the number of replacements, a pattern for the replacement, an order (starting from either the beginning or end) for the replacements, and recursive processing? This method lets you customize the replacement process for each match using callbacks or closures while specifying the order of the replacements and enabling recursive processing, giving you unparalleled control over your strings, regular expression patterns, keys, offsets, matches, limits, replacement patterns, case sensitivity, order, and recursion. 🦸♂️🧩🚀
Ahoy, adventurous coder! Buckle up for a whirlwind tour of Laravel’s string methods, where we’ll transform your text like a sorcerer with a magic wand!
__ (Feeling mysterious? Get philosophical!) class_basename (Slicing and dicing your classes like a pro!) e (Mathematics not your thing? Let Laravel handle the exponentiation!) preg_replace_array (Wielding regex like a true pattern ninja!) Str::after (Cutting off the tail end of your tales!) Str::afterLast (When the last shall be first, and the first last!) Str::apa (Styling your text in APA citation format, ‘cause who doesn’t love citations?) Str::ascii (Converting to the bare essentials of English characters!) Str::before (Finding what comes before the storm!) Str::beforeLast (The penultimate letter, unveiled!) Str::between (A tale told between two marks!) Str::betweenFirst (When you need the main part of the story!) Str::camelCase (Transforming words into humps, just like a camel on a desert quest!) Str::charAt (Finding the character at a specific coordinate, much like finding Waldo!) Str::chopStart (Lopping off unwanted words from the beginning!) Str::chopEnd (A clean end is as good as a fresh start!) Str::contains (Is it in there? Search and you shall find!) Str::containsAll (If it contains them all, it’s a veritable treasure trove!) Str::doesntContain (What’s missing? Let’s see if it ain’t there!) Str::doesntEndWith (Doesn’t rhyme with ‘movie’, or ‘candy’, perhaps?) Str::doesntStartWith (No beginning like this! Let’s see if it doesn’t start that way!) Str::deduplicate (Removing all those pesky duplicates, one by one!) Str::endsWith (Does it finish with a bang? Or does it fizzle out?) Str::excerpt (Giving just a taste of the whole story, leaving them wanting more!) Str::finish (Wrapping up nicely, ‘cause we all like a good ending!) Str::fromBase64 (Decoding that mysterious base64 message, at last!) Str::headline (Making the first letter big and bold, just like a newspaper headline!) Str::initials (Abbreviating names with initials, for brevity’s sake!) Str::inlineMarkdown (Turning your plain text into Markdown, with the magic of Laravel!) Str::is (Is it? Indeed, let us find out!) Str::isAscii (Is it all alphabet soup and numbers?) Str::isJson (Is it JSON? Let’s see if that’s the case!) Str::isUlid (Is it an unique identifier like no other?) Str::isUrl (Does it lead to a webpage, far and wide?) Str::isUuid (Is it universally unique? Let’s see!) Str::kebabCase (Transforming your words into delicious, juicy kebabs!) Str::lcfirst (Starting with a lower case letter, just like in the dictionary!) Str::length (Counting all the characters, from A to Z and beyond!) Str::limit (Setting the limit, so as not to overflow!) Str::lower (Converting it all to lower case, for those who don’t appreciate capital letters!) Str::markdown (Turning plain text into a beautifully formatted Markdown page!) Str::mask (Protecting sensitive information with clever masks!) Str::match (Is it matching? Let’s find out, detective style!) Str::matchAll (Is it matching everywhere? A global search, if you will!) Str::isMatch (Does it match the pattern? Yes, indeed!) Str::orderedUuid (Creating a UUID that’s as ordered as a well-organized library!) Str::padBoth (Adding some padding on both sides, for balance and harmony!) Str::padLeft (Padding the left side, because even text needs a little cushion!) Str::padRight (Padding the right side, keeping it all lined up neatly!) Str::password (Creating strong passwords that would put Fort Knox to shame!) Str::plural (Adding an ‘s’ or an ‘es’, depending on the rule of grammar!) Str::pluralStudly (Transforming plural words into studly, studly words!) Str::position (Finding its position in the string, like a needle in a haystack!) Str::random (Generating random text, for those who love the thrill of mystery!) Str::remove (Eliminating unwanted words, with the power of Laravel!) Str::repeat (Repeating it over and over again, like a broken record!) Str::replace (Swapping out old words for new ones, in a game of textual hide-and-seek!) Str::replaceArray (Replacing multiple words at once, like a magic spell gone wild!) Str::replaceFirst (Replacing the first instance only, no second chances here!) Str::replaceLast (Swapping out the last one, like a final act of rebellion!) Str::replaceMatches (Finding and replacing all matches in one swift move!) Str::replaceStart (Swapping out from the start, for those who love a clean beginning!) Str::replaceEnd (Replacing the end, because sometimes it’s all about the finale!) Str::reverse (Turning text backwards, like a mirror image of its former self!) Str::singular (Transforming plural words into singular words, one by one!) Str::slug (Creating an easy-to-remember URL friendly version of your text!) Str::snakeCase (Transforming your words into slithery, wiggly snakes!) Str::squish (Removing all the whitespace, for a tidy, clean look!) Str::start (Starting at a specific position, much like an epic adventure!) Str::startsWith (Does it start with this? A quick question of semantics!) Str::studlyCase (Transforming words into studly, formal words, fit for a king!) Str::substr (Cutting out a piece from the middle, like a delicious slice of cake!) Str::substrCount (Counting how many times a certain substring appears!) Str::substrReplace (Replacing a specific substring, in a surgical strike!) Str::swap (Swapping two parts of the string, like a game of musical chairs!) Str::take (Taking only a certain number of characters, for those who love a good tease!) Str::titleCase (Transforming words into proper title case, just like in a book!) Str::toBase64 (Converting it all to base64, for those who love code-speak!) Str::transliterate (Transforming text into a different alphabet system, like a secret agent on the run!) Str::trim (Removing all the excess whitespace, for a clean, elegant look!) Str::ltrim (Trimming from the left side, for those who like a tidy start!) Str::rtrim (Trimming from the right side, for a clean and finished look!) Str::ucfirst (Starting with an upper case letter, just like in a book title!) Str::upper (Converting it all to upper case, for those who shout their words!)
And that’s not all, folks! Laravel provides even more methods for string manipulation, allowing you to customize your text to perfection. Happy coding!
P.S.: All these methods are available under the ‘Str’ facade in Laravel. Don’t forget to use it!
Hope this helps! Let me know if there’s anything else I can help with.
Regards, Your Assistant.
Generated by www.meetalex.com
The String Symphony Orchestra
Welcome to the grand stage of Laravel’s Strings, where every note is a method, and the composition is as beautiful as it is versatile! Let’s dive into our collection of musical numbers:
- Encores:
after,afterLast,append– Add a little something extra to your melody. - Lyrics:
basename,dirname,file,path– Navigate through the filesystem with ease. - Tunings:
camel,kebab,studly,snake– Convert your string to various case styles like a pro! - Decryption:
decrypt,encrypt– Secure your secrets with our top-secret encryption methods. - Morphing:
apa,lcfirst,ucfirst,ucwords,ucsplit,lower,upper– Transform your string into a new shape! - Translation:
transliterate– Take your string on an international journey, converting it to different scripts along the way. - Masking:
mask– Add a little mystery to your strings with this secret-keeping method. - Substitutions:
replace,replaceArray,replaceFirst,replaceLast,replaceMatches,substrReplace– Replace one note with another to create a new harmony. - Slicing:
charAt,substr– Pluck individual characters or a specific part of your melody. - Chopping:
chopStart,chopEnd– Trim unwanted parts from the beginning or end of your song. - Splitting:
split,explode– Divide your string into an array of smaller melodies. - Excerpting:
excerpt– Create a shortened version of your longer composition. - Formatting:
newLine,trim,ltrim,rtrim,stripTags– Clean up your string and present it in its best form. - Counting:
length,wordCount,words– Keep track of the beats in your song. - Comparison:
contains,doesntContain,startsWith,endsWith,exactly,is,isAscii,isJson,isUrl,isUuid,isUlid– Find similarities and differences between your strings. - Matches:
match,matchAll,scan– Locate specific patterns in your string with these matching methods. - Synonyms:
singular,plural– Change the number of your nouns to suit your lyrics perfectly. - Spelling Correction:
whenExactly,whenNotExactly,whenIs,whenIsAscii,whenIsUlid,whenIsUuid,whenTest– Catch any spelling errors and ensure accuracy in your composition. - Punctuation:
whenStartsWith,whenEndsWith,whenContains,whenContainsAll,whenDoesntEndWith,whenDoesntStartWith– Add or remove punctuation to tailor your sound to the desired style. - Line Breaks:
wrap,unwrap– Keep your string neatly packaged or set it free! - Conversion:
fromBase64,toBase64,toHtmlString,toUri– Transform your strings into different formats for various purposes. - Special Effects:
tap,test– Test your string or add a little flair with these special methods. - Synergy:
when,whenContains,whenContainsAll,whenDoesntEndWith,whenDoesntStartWith,whenEmpty,whenNotEmpty,whenStartsWith– Combine multiple methods to create a unique harmony. - Transformations:
mask,substrReplace,swap,replaceArray,replaceMatches,replaceStart,replaceEnd,ucsplit– Modify your string in various ways to create new and exciting melodies!
Ahoy there, code pirate! Welcome to Laravel’s treasury of textual treasure – theStrings section!
Now, brace yourself for a voyage into the heart of string manipulation. In Laravel, we call this magical method __(). It’s like having Jack Sparrow as your personal wordsmith, but without the parrot or the eye patch (unless you count the PHP tags).
This enchanted helper allows you to dynamically insert variables into strings by wrapping them in curly braces. For example:
echo __('Hello :name!', ['name' => 'Cap'n Swabby']); // outputs "Hello Cap'n Swabby!"
Here, __ is your new best friend that makes your life as a Laravel developer a walk on the plank (but hopefully with fewer sharks).
But don’t worry about getting lost at sea; our trusty method also comes equipped with localization features! So, whether you’re translating for your crew or navigating international waters, __ can help set your ship’s course to smoother sailing. Just remember:
$translations = [
'greeting' => 'Hello :name!',
];
echo __('greeting', ['name' => 'Cap'n Swabby']); // outputs "Hello Cap'n Swabby!"
So, if you ever find yourself stranded on a deserted island with nothing but your trusty Laravel installation, fear not! With __, you’ll always be able to communicate effectively, even if it means sending a message in a bottle… or a view. Yarr!
Ahoy there! Prepare to embark on a linguistic adventure with Laravel’s swashbuckling __() function! This nifty pirate parrots your language files like an old sea dog, translating any provided translation string or key into the pirate dialect of your choice.
echo __('Arr matey, welcome aboard our app'); // Replace 'arr' with 'ye' if you want a more authentic pirate vibe!
echo __('messages.welcomeToTheHighSeas'); // The perfect way to greet new recruits on the open ocean!
Now here be some swashbucklingly useful information – if the specified translation string or key be walkin’ the plank, don’t ye worry none! The __() function will bravely return the given value. So in our example above, if ‘messages.welcomeToTheHighSeas’ was lost at sea, the function would return ‘messages.welcomeToTheHighSeas’, aye aye!
Anchors away, me hearties! Now that you’ve set sail with Laravel’s __() function, you’ll be fluent in pirate speak and more prepared than Captain Jack Sparrow for any international communications!
Ahoy there, code pirates! Steer clear of those longwinded, bloated class names and sail with the wind at your back using our nifty little function class_basename(). It’s like a magical compass that navigates through those treacherous waters of nested namespaces to reveal the true heart of your class.
Just fire up your trusty ship, cast anchor on any class (Foo\Bar\Baz, for example), and hoist the sails high:
$class = class_basename('Foo\Bar\Baz');
// Ta-da! The secret treasure awaits - Baz
Now, don’t you feel like a conquering explorer after unearthing the hidden riches of your class name? Arrrr, matey, you’re ready to conquer the world, one Laravel function at a time!
Alright, let’s dive into the magical world of Laravel’s e() function - a superhero that turns your HTML into something the web can understand, without getting tangled in its own cape! 🦸♂️🦸♀️
In simpler terms, it’s like giving your HTML a makeover, transforming those dangerous angle brackets and ampersands into their tamed equivalents. No more wild characters causing mayhem on your webpage! 😱
echo e('<html>foo</html>');
// Transforms into: <html>foo</html>, making it safe and sound for the web. 🛡️🌟
Just remember, with great power comes great responsibility! Using e() can make your code cleaner and safer, but don’t forget to keep an eye out for any hidden XSS vulnerabilities lurking around. Happy coding, brave Laravelers! 🚀💻
Ahoy there, matey! Buckle up for a wild ride through the treacherous seas of Laravel’s preg_replace_array() function - a pirate’s best friend when it comes to navigating the murky waters of string manipulation!
Avast, ye landlubbers! This function is a swashbuckling marvel that lets you replace a given pattern in a string using a treasure chest full of replacements (an array, if ye like). So hoist the main sail and prepare to loot some strings!
$string = 'The event will take place between :start and :end'; // Arrghh, our original string be riddled with markers!
$replaced = preg_replace_array('/:[a-z_]+/', ['8:30', '9:00'], $string); // Arrrr, here be the magic! We'll replace all those pesky markers with new times.
// The event will take place between 8:30 and 9:00 // Ahoy! Our newly looted string be as clean as a pirate's parrot (ish)!
So there ye have it, mateys! A fun way to conquer the sea of strings and replace those pesky patterns with shiny new replacements. Now, off you go to plunder more strings - yarr!
Ahoy there, shipmates! Sail with me as we delve into the nautical magic of Laravel’s Str::after() method – a compass for your string voyage! 🚢🌈
This swashbuckling function sets sail on a mission to locate and return everything that comes after a specified treasure (value) in a string map. If the treasure is nowhere to be found, it cheerfully bestows upon you the entire string as if it were a pirate’s bounty! 🏴☠️
Steer your ship to:
use Illuminate\Support\Str;
Capture the booty:
$treasureMap = Str::after('Shiver me timbers, this be my name', 'Shiver me');
You will receive:
// ' me timbers, this be my name'
Now that you’ve mastered the Str::after() method, set sail for adventure and conquer those strings! 🌴🌊🐠
Ahoy there, code pirates! Buckle up as we set sail through the murky waters of Laravel’s string manipulation with the Str::afterLast() method! This is a swashbuckling, treasure-hunting technique that helps you find everything after the last occurrence of a hidden galleon (aka the given value) in a sea shanty of a string.
If ye captain’s log should happen to omit this valuable booty from its parchment, fear not! The entire string will be bestowed upon you, like a king’s ransom on a moonless night:
Arrr matey! Let's use `Str::afterLast` to loot 'App\Http\Controllers\Controller' for anything after the last '\\':
use Illuminate\Support\Str;
$plunder = Str::afterLast('App\Http\Controllers\Controller', '\\');
// 'Controller' (Yeep, we found it!)
Yarr, matey! Now ye can pillage and plunder with precision! Avast, sail onwards to conquer new lands and hoard more gold than the pirate kings themselves!
Ahoy there, code pirates! Ever find yourself in the bewildering Bermuda Triangle of title case formatting? Fear not, for I’ve got a Laravel method that’s more navigable than a treasure map: Str::apa()!
This enchanted function converts your string into title case following the impeccably strict APA guidelines. If you’re as clueless about APA as I was before writing this, here’s what it means: capitalize the first and last words, plus any proper nouns or verbs, while leaving everything else in lowercase.
So if your string is ‘creating a project’, simply unleash Str::apa() upon it with the following incantation:
use Illuminate\Support\Str;
$title = Str::apa('Creating A Project');
// Magic happens, and you get:
// 'Creating a Project'
Now that your strings are as polished as Captain Jack Sparrow’s peg leg, set sail on the high seas of proper formatting with Str::apa()! Arr matey!
Ahoy there, matey! Prepare to embark on an exciting journey into the realm of Laravel strings, where pirate chars can turn your code into a sea monster! Fret not, for I’ve got just the remedy - Str::ascii() method, yarr!
This handy dandy method, much like Captain Jack Sparrow’s compass, will guide you through transliterating your string into ASCII values. It’s a swashbuckling way to keep those pesky pirate chars at bay, ensuring your code stays clean as a ship’s deck!
Here’s a whale of a tale:
Arrr matey! Use the mighty `Illuminate\Support\Str` and let `Str::ascii()` work its magic on this pesky 'û' char:
$slice = Str::ascii('û');
// ta-daa! A simple 'u' will be left in its wake.
Now you can sail the seas of Laravel code without fear of those unwanted pirate chars steering your ship aground! Keep it up, and one day you might just have a codebase as shiny as Captain Barbossa’s doubloons!
Ahoy there, coding sailors! Steer your boats towards the mighty Str::before() method - a nautical navigation tool that’s as handy as a compass but works with strings instead of stars!
If you’ve ever found yourself longing to pluck out all the text before a specific treasure (or in our case, substring) from your string, this is the function you’d want to hoist the anchor for!
use Illuminate\Support\Str;
$booty = Str::before('Ahoy mateys! Here be my buried treasure', 'my buried');
// Result: 'Ahoy mateys!'
Just like a pirate seeking gold, now you too can find the hidden gems in your strings with this swashbuckling method!
Ahoy there, code wranglers! Ever found yourself in a pickle, trying to separate the wheat from the chaff in your string like a digital Goldilocks? Well, buckle up, because we’ve got just the tool for you - Str::beforeLast()!
This cunning little method is akin to a stringy game of hide and seek, where it reveals everything before the last hiding spot of a specific string value. Let’s dive into an example to see it in action:
use Illuminate\Support\Str;
$hiddenTreasure = 'This is my name';
$lastHideout = 'is';
$foundPirateName = Str::beforeLast($hiddenTreasure, $lastHideout);
// 'This ' (but we prefer to imagine it as 'Captain Longbeard')
So, if you’ve got a string and are looking for the part that comes before the last occurrence of another specific string, Str::beforeLast() is your new best friend. Keep this one in your coding arsenal and impress your fellow coders with your newfound string-slicing skills! Yarr!
Ahoy there, coder! Buckle up for a wild ride through the vibrant world of Laravel strings! Today, we’re diving deep into the mesmerizing depths of the Str::between() method - a magical technique that’ll make you feel like a digital Houdini, slicing and dicing strings with ease.
use Illuminate\Support\Str; // Importing Str is akin to summoning the ancient spirit of strings!
$mysterySlice = Str::between('This is my name', 'This', 'name'); // Here we're asking Str to reveal the mystery between 'This' and 'name'. It's like asking where the cheese is hidden in a riddle-filled maze, but for strings!
// ' is my ' – Ta-da! The secret ingredient has been revealed!
So there you have it, folks. With Str::between(), you can now uncover hidden gems in your strings like a modern-day Indiana Jones, or a digital Sherlock Holmes for strings – either way, it’s an incredibly useful tool to add to your Laravel arsenal!
Ahoy there, code pirates! Sail the seas of strings with Str::betweenFirst, a swashbuckling Laravel method that’ll make your coding shipshape and Bristol fashionable!
This magical function is like the parrot on your shoulder, screeching out the tiniest piece of your string that lies between two treasure chests:
Grab your peg leg and let's dive in! 🦭
use Illuminate\Support\Str;
$swaggy_loot = Str::betweenFirst('[a] bc [d]', '[', ']');
// Treasure found, matey! It's just 'a'! 🏴☠️🌴
Remember to keep your hooks sharp and your compass calibrated – happy sailing, ye landlubbers! 🐙🌊✨
Ahoy there, coding buccaneers! Steer your keyboards towards the Str::camel() method - a nautical navigator for text formatting that’ll have your strings sailing smoothly through the treacherous waters of case inconsistency.
Grab the wheel, mateys! \ use Illuminate\Support\Str;
Let's hoist the 'Underscore Jolly Roger', shall we? Str::camel('foo_bar');
Batten down the hatches and prepare for a transformation –> 'fooBar' you'll soon be saying, as this method converts our underscore-infested string into pristine camelCase.
Arrrr, that's one swashbuckling tool to have in your coding arsenal!
Ahoy there, coding cowpoke! Wanna wrangle some characters like a boss? Saddle up with the `Str::charAt()` method! This lasso-like function snatches a single character from your haystack (string) and ties it down at the index you provide.
But remember, cowboy, this ain't the Wild West—you gotta keep those indices in check. If you roam off the edge of the string, all you'll find is an ol' false positive. Here's how to rope in some action:
```php
use Illuminate\Support\Str;
$character = Str::charAt('This is my name.', 6);
// 's' - The sixth character from the start, ready for a saloon showdown!
Now go forth and lasso those characters, partner! And remember: in this frontier, it’s all about str-e-e-t-ching your coding skills. Yeehaw!
Ahoy there, code pirates! Steer clear of those pesky leading characters with the swashbuckling Str::chopStart() method! This mighty function is like a trusty old parrot that repeats only the first thing it hears at the beginning of your string. If you don’t want it anymore, just toss it overboard!
use Illuminate\Support\Str; // Don't forget your ship's provisions!
$url = Str::chopStart('https://laravel.com', 'https://'); // Farewell, anchor, you're no longer needed!
// Treasure awaits: 'laravel.com'
If ye be sailing with a crew of unruly characters, Str::chopStart() can handle an array of them! If any of those ne’er-do-wells are hanging around at the start of your string, it’ll boot ‘em off!
use Illuminate\Support\Str; // Your crew needs to be well-provisioned too!
$url = Str::chopStart('http://laravel.com', ['https://', 'http://']); // Captain Hook and Smee, we no longer need ye!
// The voyage continues: 'laravel.com'
Yarr, matey! Now your strings are as tidy as a ship’s cabin, and you can navigate the seas of code with ease!
Ahoy there, shipmates! Let’s hoist the sails of knowledge and set sail on a Laravel adventure with the swashbuckling Str::chopEnd() method!
This fearless function is like the trusty cutlass of string manipulation. Its mission? To remove the last appearance of a specific value from a string, but only if it’s found at the end of the pirate ship! Arr matey!
Here’s an example that will make you shiver your timbers:
use Illuminate\Support\Str;
$file = Str::chopEnd('app/Models/Photograph.php', '.php');
// 'app/Models/Photograph' (the .php has been sent to Davy Jones' Locker!)
But wait, there’s more! This method isn’t just a one-trick pony; it can handle an entire treasure chest of values. Simply pass in an array as the second argument:
use Illuminate\Support\Str;
$url = Str::chopEnd('laravel.com/index.php', ['/index.html', '/index.php']);
// 'laravel.com' (both the /index.html and /index.php have been tossed overboard!)
Now that you’ve got your sea legs, keep sailing through the Laravel documentation for more exciting adventures! Happy coding! 🍻 🏴☠️
Oh, the Str::contains() method! It’s like the Sherlock Holmes of strings, but instead of solving mysteries, it finds stuff within other strings. By default, it’s as picky as a cat on a hot tin roof: it insists on exact matches and won’t accept any shenanigans with uppercase or lowercase letters.
use Illuminate\Support\Str;
$isContained = Str::contains('This is my name', 'my'); // Yes, it knows 'my'!
// true, because it's a match made in... well, not heaven, but somewhere nearby.
But what if you want to broaden your search? You can pass an array of suspects and let Str::contains() be the judge.
use Illuminate\Support\Str;
$isContained = Str::contains('This is my name', ['my', 'foo']); // It's a free-for-all in this string!
// true, because 'my' and 'foo' are both present, but remember: this method doesn't do math.
Now, you might think, “Hey, what if I want to ignore case sensitivity?” Well, my friend, all you have to do is set the ignoreCase argument to true:
use Illuminate\Support\Str;
$isContained = Str::contains('This is my name', 'MY', ignoreCase: true); // Now we're talking!
// true, because 'MY' and 'my' are now BFFs, just like that.
And there you have it! With Str::contains(), you can find anything from ‘a’ to ‘z’, even if they decide to play dress-up with each other!
Ahoy there, coding pirate! Ever found yourself in a pickle, trying to figure out if your swashbuckling yarn contains all the necessary ingredients? Well, fear no more, matey! Introducing Str::containsAll() - the magical method that’ll help you steer clear of those shark-infested seas of doubt.
Here’s how ye can use it:
use Illuminate\Support\Str;
$gotAllMeMateys = Str::containsAll('This is me captain's log', ['me', 'captain']);
// true, hooray! All crew members accounted for!
But what if ye want to let loose the anchor and allow for some wordplay? Fear not! With the ignoreCase argument set to true, this method will search through the seas of your text without caring if ‘MY’ is spelled as ‘my’.
use Illuminate\Support\Str;
$gotAllMeMateys = Str::containsAll('This is me captain\'s log', ['MY', 'NAME'], ignoreCase: true);
// true, whew! Even the case-shy can be found.
Yarr, now ye have no reason to go into mutiny when trying to find all your mates in a string! Happy coding, mateys! 🏴☠️🎉
Oh, the Str::doesntContain() method! It’s like a picky eater for strings. It refuses to budge if it spots the specified value in a string, no matter how camouflaged or disguised it is.
By default, this discerning little fellow plays by the strict letter of the law - case sensitive, no exceptions:
use Illuminate\Support\Str;
$isPicky = Str::doesntContain('This is name', 'my'); // A true friendship it does not find.
But fear not! If you’ve got a wild card in your deck, you can pass an array of values to this snazzy method:
use Illuminate\Support\Str;
$isPicky = Str::doesntContain('This is name', ['my', 'framework']); // Ah, at last! A string that fits the bill.
And if you’re dealing with a particularly capricious string, you can set the ignoreCase argument to true, making it less finicky about case:
use Illuminate\Support\Str;
$isPicky = Str::doesntContain('This is name', 'MY', ignoreCase: true); // Now we're talking!
And there you have it, a friendly guide to string pickiness in the wild west of Laravel land. Enjoy your newfound skills, cowboy (or cowgirl)!
Ahoy there, coders! Let’s embark on a charming journey through the enchanted forest of Laravel Strings with our trusty sidekick Str::deduplicate()!
This magical method is like a one-man band, playing only unique notes from your string symphony. You see, it removes repetitive instances of a character, making sure no two consecutive notes sound the same (unless you want them to, of course). By default, it polishes off those pesky excess spaces:
use Illuminate\Support\Str;
$result = Str::deduplicate('The Laravel Framework');
// Out goes the excessive space-ness, leaving us with 'The Laravel Framework'
But what if you want to deduplicate a different character? No problemo! Just pass it in as the second argument:
use Illuminate\Support\Str;
$result = Str::deduplicate('The---Laravel---Framework', '-');
// The-Laravel-Framework emerges, ready to impress your code reviewers!
Now, wasn’t that a jolly good time? Keep strumming those strings, mates! 🎸🐘🌴
Ahoy there, code swashbucklers! Prepare to embark on a thrilling adventure with the Laravel Str::doesntEndWith() – the pirate of string terminations! 🏴☠️
Are you tired of your strings ending up in places they shouldn’t? Well, no more walking the plank for them! With our trusty doesntEndWith() method, you can ensure that your strings never land a kiss on the tail of unwanted characters. 🐠
Let’s hoist the sails and set sail on an example:
use Illuminate\Support\Str;
$result = Str::doesntEndWith('This is my name', 'dog'); // Arrgggh! It ain't no dog!
// true, thankfully our string be safe from sea dogs.
But what if ye be fearin’ a mutiny of multiple outlaws? Fear not! doesntEndWith() can handle arrays o’ ne’er-do-wells:
use Illuminate\Support\Str;
$result = Str::doesntEndWith('This is my name', ['this', 'foo']); // Phew, no matches be found!
// true, the string be safe from impostors.
$result = Str::doesntEndWith('This is my name', ['name', 'foo']); // Drat! A match be made!
// false, the string be doomed to have a name or a phony 'foo' on its tail.
So hoist the Jolly Roger high and keep those strings in line with the Str::doesntEndWith() method! Arr me hearties, be sure to remember that with great power comes great responsibility – ya hear? 🏴☠️
Ahoy there, fellow coder! Ever found yourself in a pickle, trying to figure out if your string isn’t as fancy as some posh prefix you got? Well, worry not! Laravel’s Str::doesntStartWith method is here to help you untangle that Gordian knot.
Imagine you’re at a cocktail party, but instead of names, everyone has strange string labels pinned on their chests. You want to find the one who isn’t wearing ‘That’, but you can’t remember anyone without a ‘What’ or ‘There’ either. Instead of awkwardly asking each guest, just let Str::doesntStartWith do the job for you!
use Illuminate\Support\Str;
$party_guest = 'This is my name'; // Hopefully not named "That"
$excluded_prefixes = ['What', 'There']; // No need to worry about "That" though
if (! Str::doesntStartWith($party_guest, $excluded_prefixes)) {
echo "Found a match! Yay, it's not wearing any of the undesirable prefixes.";
} else {
echo "Sadly, everyone seems to be donning those undesirable prefixes. Time for another round?";
}
See how easy that was? With Str::doesntStartWith, your life just got a whole lot less awkward at cocktail parties and a whole lot more efficient in the code world!
Ah, the Str::endsWith() method! The magical string sorcerer that’ll make your code dance like a troupe of digital divas. This enchanting function will tell you if Cinderella (your string) has lost her glass slipper (the value you’re looking for) at the ball - all without having to worry about midnight striking! 🕰️
Here’s how it works:
use Illuminate\Support\Str;
$dancingCinderella = 'This is my name'; // Your string, likely not a royal
$glassSlipper = 'name'; // The value you're hoping to find at the ball
$ballroomSearchResult = Str::endsWith($dancingCinderella, $glassSlipper);
// true - Cinderella's found her glass slipper! Time for the pumpkin carriage!
But what if you’re attending a polygamous ball with multiple glass slippers? No worries, Str::endsWith() is equipped to handle such ballroom intrigue:
use Illuminate\Support\Str;
$multipleBalls = ['name', 'foo']; // An array of possible glass slippers
$manyBallsSearchResult = Str::endsWith($dancingCinderella, $multipleBalls);
// true - Cinderella's found a match in one of the balls! Time to leave before Prince Charming discovers the chaos...
Of course, not every dance partner at the ball is Cinderella:
use Illuminate\Support\Str;
$notCinderella = 'This is my name'; // A non-royal string, alas
$wrongBalls = ['this', 'foo']; // Glass slippers that don't belong to Cinderella
$wrongMatchResult = Str::endsWith($notCinderella, $wrongBalls);
// false - Cinderella did not find a match in these balls. Time for another dance? 💃🕺
Now that you’ve got your very own digital fairy godmother (or father) in Str::endsWith(), your Laravel applications will be as graceful and elegant as the royal ball! 👑✨
Ahoy there, Laravel swashbucklers! Let’s dive into the enchanting realm of Str::excerpt(), a method that would make even the Bard himself envious. This magical spell extracts a tantalizing excerpt from a string, homing in on the first occurrence of a phantom phrase.
use Illuminate\Support\Str;
$excerpt = Str::excerpt('Once upon a time...', 'time', [
'radius' => 3
]);
// '...upon a ...' (Just like a knight who gallops off, leaving the rest of the tale behind)
The radius option, not to be confused with a medieval unit of measurement, sets the number of characters that should surround the truncated string, ensuring it doesn’t feel too lonely. By default, it’s as broad as the Great Wall of China – 100 characters.
Now, imagine you were writing an epic poem and wanted to add some flair to your truncation. The omission option lets you define what should be prepended and appended to the excerpt:
use Illuminate\Support\Str;
$excerpt = Str::excerpt('This is my name', 'name', [
'radius' => 3,
'omission' => '(drumroll please) '
]);
// '(drumroll please) my na...' (A dramatic touch to your abbreviated string)
Remember, with Str::excerpt(), you can weave tales that are both captivating and succinct – just like a well-crafted haiku! So go forth, my friends, and excerpt with abandon! 🏹
Ahoy there, coding pirates! Time for a bit of string sailing with Laravel’s Str::finish() method – the seafaring sailor of character appending! 🌞
This swashbuckling method takes a string and adds a single pirate’s chest worth of your chosen treasure (er, value) at the end, only if it ain’t already there like a parrot on its shoulder.
use Illuminate\Support\Str;
$arrrrranged = Str::finish('this string', '/'); // this string/
And if your string is already adorned with the treasure you seek, it'll leave it be like a well-behaved parrot – 'tis no bother!
$arrrrranged = Str::finish('this string/', '/'); // this string/ (no change)
Now go forth and append like a seasoned mariner, with Laravel’s Str::finish() guiding your way! 🏴☠️🚀
Ahoy there, coders! Step right up and feast your eyes on the spectacle that is Str::fromBase64() – the Barnum & Bailey of decoding, the Laugh-In of legible data! This magnificent method will take your Base64 string (which may or may not have been acquired through nefarious means), and transform it into something you can understand without needing a Rosetta Stone.
Let’s see it in action:
use Illuminate\Support\Str;
$decoded = Str::fromBase64('TGFyYXZlbA==');
// Laravel... because programming should be fun, not a cryptogram puzzle!
So, if you’re looking to decipher a message hidden in plain sight (but with all the subtlety of a neon sign), give Str::fromBase64() a whirl! It’s like having a personal Charles Babbage with a sense of humor.
Oh, the Str::headline() method is a real party starter in the Laravel world! It’s like a superhero of string formatting, taking your text and transforming it into something that looks like it belongs on a marquee.
Imagine you’ve got yourself a string all jumbled up, delimited by casing, hyphens, or underscores—it might as well be hieroglyphics for all the sense it makes! But fear not, for Str::headline() is here to save the day!
use Illuminate\Support\Str; // Don't forget to call in the big guns (or in this case, the big Str class)
$headline = Str::headline('steve_jobs'); // Say hello to Steve Jobs!
// Or if you prefer the digital kind of mail:
$headline = Str::headline('EmailNotificationSent'); // It's now Email Notification Sent!
Just remember, this method is only interested in your words’ first letters. It doesn’t care about their feelings or any potential capitalization drama. If you need a shoulder to cry on, we’re here for you—but for proper sentence case, check out Str::title(). Because with great power comes great responsibility!
Ahoy there, coders! Meet your new BFF - Str::initials(), the stringy spin doctor who’s got the scoop on your monikers!
No more guessing games about figuring out those initials. Just pass it your full name and watch the magic happen:
use Illuminate\Support\Str;
$initials = Str::initials('taylor otwell'); // Gives: T O
But wait, there’s more! If you fancy capitalizing those initials to make them look sharp and official, just add the capitalize: true argument. It’s like giving your initials a power suit!
$initials = Str::initials('taylor otwell', capitalize: true); // Gives: TO
So go ahead and impress your friends with your newfound superpower, or maybe just make it easier for those pesky autocomplete features to recognize you. Either way, Str::initials() is here to help!
Ahoy there, code pirates! Ever found yourself in a pickle, trying to turn Markdown into HTML in Laravel, but without the pesky block-level elements giving you trouble? Well, shiver me timbers! The Str::inlineMarkdown() method is your new best mate!
This swashbuckling helper converts GitHub flavored Markdown into inline HTML using CommonMark, a markup language that’s as sharp as Captain Hook’s hook and just as reliable. But don’t let its piratey name fool ya—it ain’t the same ol’ markdown method!
With this method, you can turn your plain-text parrots (Laravel) into bold, beautiful anchors without having to worry about those pesky block-level elements getting in the way:
use Illuminate\Support\Str;
$html = Str::inlineMarkdown('**Laravel**');
// Result: <strong>Laravel</strong>
Now, don’t be a landlubber and miss out on this handy helper! It’ll make your markup life smoother than butter in a pirate’s beard. Arrrr!
Ahoy there, coding pirates! Laravel’s got some swashbuckling advice for ya regarding Markdown Security! Ye see, by default, Markdown is as friendly as a drunken sailor to raw HTML. This can lead to Cross-Site Scripting (XSS) vulnerabilities, which ain’t good news for any ship.
Fret not, mateys! The CommonMark Security documentation is here to guide us through the stormy waters of HTML chaos. Yar, you can use the html_input option to either escape or strip raw HTML, and the allow_unsafe_links option to decide whether to let suspicious links onboard your vessel.
If ye need to allow a bit o’ raw HTML, make sure yer compiled Markdown sails through an HTML Purifier before setting sail:
use Illuminate\Support\Str;
// Inject: <script>alert("Hello XSS!");</script>
Str::inlineMarkdown('Inject: <script>alert("Hello XSS!");</script>', [
'html_input' => 'strip',
'allow_unsafe_links' => false,
]);
// Inject: alert("Hello XSS!"); - HTML Purifier did its job!
Now that’s what I call a shipshape solution to keep those treacherous XSS vulnerabilities at bay. Happy hacking, mateys! 🏴☠️
Ahoy there, intrepid developers! Today we’re sailing the seven seas of strings with a mighty method that’s sure to set your code aglow: Str::is(). This swashbuckling helper is here to tell you if one string has walked the plank and ended up as a match for another. How does it do this, you ask? Like a pirate deciphering a treasure map, with wildcards!
use Illuminate\Support\Str;
$matchesArrr = Str::is('foo*', 'foobar'); // True-ho! Arr-rgh-hoy!
$matchesArrr2 = Str::is('baz*', 'foobar'); // False alarm, mateys!
But what about those times when Captain Grammar insists on lower or upper case letters? Fear not, me hearties! By setting the ignoreCase argument to true, we can sail these treacherous waters with ease:
use Illuminate\Support\Str;
$matchesArrr3 = Str::is('*.jpg', 'photo.JPG', ignoreCase: true); // Yarrr, it matches!
So hoist the mainsail and set a course for success with Str::is(). Happy sails, landlubbers!
Ahoy there, coders! Let’s dive into the wild world of Laravel strings, shall we? Today’s star is none other than the Str::isAscii() method. This little gem is like a superhero for your text, ensuring it’s as pure and simple as a one-liner in a sitcom script!
use Illuminate\Support\Str; // Yes, we're about to get technical, but don't worry, it won't hurt a bit.
$isAsciiTaylor = Str::isAscii('Taylor'); // Guess what? It's a big 'ol YES! Taylor is 7-bit ASCII all the way.
$isUmlaut = Str::isAscii('ü'); // Well, this umlaut character is feeling a bit left out. Sorry buddy, you're a NO.
So, next time your string is throwing a party and you want to make sure it doesn’t invite any binary guests (you know, those characters with funny accents), just call in the Str::isAscii() method! It’ll be your reliable guard at the gate, ensuring only the good ol’ 7-bit ASCII characters make it to the bash. Happy coding, and remember: Keep it simple, stupid! (KISS - but let’s keep it friendly here!) 😉
Ahoy there, code pirates! Sail the seas of data with Str::isJson(), the swashbuckling string validation method that’ll keep your JSON shipshape and Bristol fashion! 🌴🚀
This nifty function dives deep into your strings, searching for the elusive treasure chest of valid JSON. But beware, matesy – it won’t take kindly to any ol’ string that ain’t properly structured!
use Illuminate\Support\Str;
$treasure_found = Str::isJson('[1,2,3]'); // Arr matey! Gold coins galore!
$treasure_found = Str::isJson('{"first": "John", "last": "Doe"}'); // Another chest of precious jewels found!
// But beware, these aren't the treasures ye be lookin' for!
$treasure_not_found = Str::isJson('{first: "John", last: "Doe"}'); // Sorry mate, keys and values must be in quotes!
Happy JSON hunting to one and all! 🏴☠️🌟
Ahoy there, matey! Buckle up as we dive into the swashbuckling world of Laravel’s Str::isUrl() method - a beacon of hope for sailors lost at sea (or developers stuck with dodgy URLs).
This trusty function is like the reliable compass on your pirate ship, helping you determine if a given string is navigable web territory. All you need to do is cast it a spell:
use Illuminate\Support\Str;
$isUrl = Str::isUrl('http://example.com'); // Ahoy! It's true matey, a proper URL!
$isUrl = Str::isUrl('laravel'); // Alas, it seems we have a landlubber's grasp of the seas. False!
But wait! What if you only trust the seven seas of ‘http’ and the icy waters of ‘https’? No worries, matey! You can specify your preferred protocols:
$isUrl = Str::isUrl('http://example.com', ['http', 'https']); // Arrgh! Only accept these two, ye scurvy dogs!
And there you have it! A fun-filled pirate adventure with Laravel’s Str::isUrl() method. Yarr, set sail for success in your web development journey!
Ahoy there, matey! Steer clear of the shark-infested waters of ULID validation with the swashbuckling Str::isUlid() method!
Hoist the sails and set course for this Laravel gem, as it’ll help you avoid the scurvy of dealing with invalid ULIDs. Here’s how ye can use it:
Arrrgh, bring me the `Str` class, ye landlubbers!
$isULIDValid = Str::isUlid('01gd6r360bp37zj17nxb55yv40');
// Aye aye captain, it returns true - a proper ULID indeed!
But if ye try to pass 'laravel' to the `Str::isUlid()`, you'll find yerself in Davy Jones' Locker:
$isULIDValid = Str::isUlid('laravel');
// Yo ho ho, it returns false - that be no ULID, matey!
May this method save your ship from the clutches of unruly ULIDs, and may your treasure chest overflow with knowledge and laughter! 🏴☠️🤝🎉
Alright, let’s dive into the ocean of UUIDs with Str::isUuid(), a method that’s more charming than a sea otter and just as adept at swimming through strings!
This little helper checks if your string is a well-behaved UUID (Universally Unique Identifier), like saying ‘hello’ in Martian to an alien:
use Illuminate\Support\Str;
$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de');
// It's like discovering a hidden treasure map in your spam folder, yes it's a UUID!
$isUuid = Str::isUuid('laravel');
// Nope, this string sounds more like a tasty pizza topping than a UUID.
But wait, there’s more! You can even validate that your UUID follows the specific version (1, 3, 4, 5, 6, 7, or 8) by setting the version option like ordering a custom-made suit:
use Illuminate\Support\Str;
$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de', version: 4);
// Voila! The perfect fit, this UUID matches the specified version 4.
$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de', version: 1);
// Oh dear! This UUID is like trying to wear a tuxedo at a beach party, it just doesn't fit.
Happy UUID hunting!
Ahoy there, matey! In the vast sea of Laravel code, we’ve stumbled upon a gem called Str::kebab(). It’s not just a method, it’s a pirate’s treasure map for your string transformations! 🏴☠️
Ever find yourself lost at sea trying to navigate through camelCase waters? Well, fret ye not! This method will turn your ‘fooBar’ into the navigable shores of ‘foo-bar’. It’s like converting Morse code into English, but with more rum and less tapping. 🌴🍹
Here’s a swashbuckling example:
use Illuminate\Support\Str;
$navigableIsland = Str::kebab('fooBar');
// voila! foo-bar, your new port of call ⛵️
Smooth sailing, captain! Now set course for the kebab-case archipelago and navigate your way to coding success! 🚀🌴
Ahoy there, coding pirates! Sail the seas of syntax with the trusty Str::lcfirst() method! This nautical navigator ensures your first character sets sail on a lowercase voyage.
Shiver me timbers! Let's bring in Str::lcfirst('Foo Bar')!
Arrr, ye'll find ol' 'foo Bar' as the result! (Just remember to keep the rest of your text safe and capitalized!)
Yo ho ho and a Laravel-full of fun!
Ahoy there, code pirates! Hoist the sails of knowledge, for we’re about to set sail on a nautical adventure of strings and lengths! We present you with the swashbuckling Str::length() method, a mariner’s compass in the vast sea of text!
In simpler terms (and let’s be honest, who doesn’t love a good pirate analogy), this bad boy tells ye how many alphabetical characters are lurking within yer string. No more counting ‘em one by one like a landlubber, just feed it your string and voila! Instant length revealal!
Arrr, mateys! Use Illuminate\Support\Str;
$lengthOftheSea = Str::length('Laravel');
// 7 pieces of eight (aka the number 7)
So there ye have it! A lively tale of a humble method that packs quite the punch. Now go forth and conquer those strings, you scurvy sea dogs! But remember, just like in piracy, safety is key – make sure to check for null or empty strings before setting sail on your string length expedition! Yarr!
Alrighty, let’s dive into the hilarious world of Str::limit(), Laravel’s trusty string-chopping sidekick!
Imagine you’ve got a tongue twister stuck in your head like a stubborn popsicle stick: “The quick brown fox jumps over the lazy dog.” But you need to share it on Twitter, and that 280 character limit is looming ominously. Fret not, dear friend! Str::limit() is here to save the day!
use Illuminate\Support\Str;
$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20);
// "The quick brown fox..." - A tweet-sized tongue twister!
But what if you’re not a fan of ellipses and want something more creative? Well, Str::limit() can be as stylish as a penguin in a tuxedo! Just pass it a third argument:
$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)');
// "The quick brown fox (...)". Now that's a sophisticated tweet!
And if you’re worried about chopping words in half like a poorly-aimed guillotine, have no fear! Str::limit() has got your back with the preserveWords argument. When set to true, it guarantees a clean, word-respecting cut:
$truncated = Str::limit('The quick brown fox', 12, preserveWords: true);
// "The quick..." - A perfectly polite phrase!
So next time you’re faced with a string longer than your cat’s tail (and we all know how long that can be), remember your trusty helper Str::limit(). It’ll make those wordy woes disappear faster than spaghetti at an Italian feast! 🍝
Ahoy there, coding seafarers! Steer clear of those rambunctious uppercase letters that’ve snuck into your code like a band of pirates looting treasure chests labeled ‘LARAVEL’. Fear not, for the mighty Str::lower() method is here to save the day!
This swashbuckling helper transforms your rowdy strings into obediently quiet lowercase ones. Behold its magical powers:
Arrr matey! Grab yer compass, hoist up the anchor, and prepare for a voyage:
use Illuminate\Support\Str;
$peaceful_harbor = Str::lower('LARAVEL');
// laravel - now a peaceful land for all to understand!
Now that’s what I call a mutiny, turning those unruly capitals into humble lowercase letters as quick as you can say “Shiver me timbers!” Don’t be a stubborn parrot insisting on uppercase, embrace the change for smoother sailing!
Hey there, programming pals! Dive into the enchanting world of Laravel with our magical Str::markdown() spellcaster! This bewitching method turns your GitHub-flavored Markdown spells into captivating HTML potions using the powerful sorcery of CommonMark. 🔮
use Illuminate\Support\Str;
// Transform a heading into an enchanted <h1> tag, leaving you spellbound!
$html = Str::markdown('# Laravel');
// <h1>Laravel</h1>
// But wait, there's more! Use the 'strip' argument to strip away unwanted boldness from your potion:
$html = Str::markdown('# Taylor <b>Otwell</b>', [
'html_input' => 'strip',
]);
// <h1>Taylor Otwell</h1> 🏆 (Boldness be gone!)
Remember, with great power comes great responsibility - don’t cast these spells without understanding their potency! Happy coding, wizards! 🤓✨
Ahoy there, code wranglers! π Letβs talk about Markdown security, shall we? π»π
By the shores of default settings, Markdown is like a friendly dolphin that leaps through waves of raw HTML. But when you feed it raw user input, it can accidentally spew out Cross-Site Scripting (XSS) vulnerabilities faster than you can say “code-sickness”! ππ§
But fear not, dear friend! The CommonMark Security documentation is like a lighthouse guiding us through the stormy seas. You can use the html_input option to either sanitize or strip raw HTML from your Markdown as easily as ordering a pint at the local pub! πΈ And the allow_unsafe_links option lets you decide whether it’s okay to let unsafe links wander into your sandbox. π
Now, if you want to let some raw HTML play in your Markdown pool party, you should pass your compiled Markdown through an HTML Purifier. Itβs like having a lifeguard on duty, making sure everyone plays safely!
use Illuminate\Support\Str;
Str::markdown('Arrr matey, I'm bringing in some raw HTML: <script>alert("Hello XSS!");</script>', [
'html_input' => 'strip',
'allow_unsafe_links' => false,
]);
// And now you get something like: <p>Arrr matey, I'm bringing in some raw HTML: alert("Hello XSS!");</p>
So there ye have it, mates! Markdown security made as fun as a buccaneer’s treasure hunt! π€΅πΌπ
Ahoy there, coding cowboys and code sorceresses! Step right up for the Laravel magic trick that’ll leave your data as secure as Fort Knox (but way less gold-y). Meet the Str::mask() method – a superhero cape for your strings! 💪💥
This isn’t just any ordinary string method; it’s more like a friendly neighborhood string disguiser, transforming your sensitive data into a secret agent’s codebook. Email addresses and phone numbers, for instance, can now be cloaked in mystery with this super-powered masker!
use Illuminate\Support\Str;
$email = Str::mask('[email protected]', '*'); // ta*****[email protected]
But that’s just the tip of the iceberg, partner! If you want to mask from the tail end like a boss, simply provide a negative number as the third argument:
$email = Str::mask('[email protected]', '*', -15, 3); // tay***@example.com
Now you can protect your data without breaking a sweat (or a budget for actual superhero costumes). Happy masking! 🎭🚀
Ah, the Str::match()! The superhero of string parsing in Laravel’s expansive universe. It’s like having a pocket-sized Sherlock Holmes who can find the needle in the regex haystack for you.
Let’s say you’re hosting a secret spy party and you want to know who’s bringing the ‘bar’. No problem! The Str::match() is your man (or woman, or robot, whatever floats your boat).
use Illuminate\Support\Str;
$spyWithBar = Str::match('/bar/', 'foo bar');
// 'bar' - Our mystery spy has been revealed!
But what if you want to know more? Like, who’s bringing the whole drinks menu? Fear not, dear detective! With the Str::match(), you can even find the ‘bartender’.
$secretDrinkMenu = Str::match('/foo (.*)/', 'foo bar');
// 'bar' - Our secret drink menu has been unveiled!
In these examples, the Str::match() method is like a magical lens that zooms in on the specific part of a string that matches your desired pattern. It’s regex-perception at its finest!
Ahoy there! Buckle up, code wranglers! We’ve got a little dance number for you called Str::matchAll() – the party starter of Laravel’s string-wrangling ensemble.
Imagine you’re spinning disco records and the crowd’s going wild, but instead of tunes, we’re talking strings! 🎼🕺💃 This method will scour through a string for fragments that match your groovy regular expression pattern like it’s a treasure hunt in cyberspace.
use Illuminate\Support\Str;
$result = Str::matchAll('/bar/', 'bar foo bar');
// It's showtime! The results will serve you up two sweet "bars" on a silver platter: collect(['bar', 'bar']) 🥃🍲
But what if you wanna focus on just one groupie in the crowd? Fear not, my friends, for Laravel can help! If you specify a matching group within the expression, it’ll return a collection of the first matcher’s groupies’ matches:
use Illuminate\Support\Str;
$result = Str::matchAll('/f(\w*)/', 'bar fun bar fly');
// The results will whisper "un" and "ly" into your ear: collect(['un', 'ly']) 🎤🔊
And if the dance floor turns out to be a dud, don’t worry – an empty collection will be your backup DJ, keeping the tunes spinning until you find the rhythm. 💃🕺🎉
Ahoy there, code wranglers! Sail the seas of string manipulation with the swashbuckling Str::isMatch()! This nautical navigator will boldly sally forth and determine if your stringy sailor speaks the language of a given regular expression. Just like a parrot that can mimic any pirate’s favorite curses, but less colorful.
Shiver me timbers! Import Str from Illuminate\Support:
use Illuminate\Support\Str;
Set sail for adventure by calling upon the `Str::isMatch()` method:
$result = Str::isMatch('/foo (.*)/', 'foo bar');
Now hoist the jolly roger of triumph, me hearties! The ship has returned with a resounding "Aye-aye, captain!" - true as a pirate's gold doubloon!
But beware the Kraken of misinterpretation! If you navigate to 'laravel', the result will be as cold as Davy Jones' locker: false.
Ahoy, coders! Dive not into the abyss of jumbled UUIDs, but rather sail smoothly with the Str::orderedUuid() method - the lighthouse guiding your database columns to a more organized shore.
This handy function spits out a “timestamp first” UUID that’s as easy on the database index as a well-oiled seagull. Once you’ve hoisted this UUID, it’ll find its proper place in line among other UUIDs generated by the method:
use Illuminate\Support\Str; // Importing Str is like grabbing a compass before setting sail!
return (string) Str::orderedUuid(); // And here's the captain's command to set your course for organized UUIDs!
Now that’s a sea change for the better, eh? Happy coding, mateys! 🌴🐘🦈
Oh, hello there! Let me introduce you to the Str::padBoth, a superhero for your strings that’s been secretly watching over your PHP scripts. This guy is like Batman (if Batman could pad strings), making sure your strings are always the right length for any situation.
use Illuminate\Support\Str;
$padded = Str::padBoth('James', 10, '_'); // Now James has some cool new pals: _ and _
// '__James___'
Or if you're feeling a bit more zen...
$padded = Str::padBother('James', 10); // Spaces around James, giving him room to breathe
// ' James '
Now you can pad your strings with any character you want (except for commas, seriously, don’t do that) and control the length just by changing a number. It’s like having a personal string stylist!
Ahoy there, code cowboys and coding cosmonauts! Let’s chat about a little Laravel gem that goes by the name of Str::padLeft(). It’s like a lasso for your strings, but instead of roping cattle, it’s all about making them look swell!
Imagine you’ve got a wild mustang named “James” and you want to put him in a corral that’s exactly 10 cacti wide. Now, poor James is a bit on the lean side and only takes up 5 cacti. What does one do? Fear not! Str::padLeft() to the rescue!
use Illuminate\Support\Str;
$padded = Str::padLeft('James', 10, '-=');
// Voila! Now you've got yourself a nicely padded James, all ready for his corral: '-=-=-James'
Now, if you just want to fill in the empty spaces with something less flashy, here's what you do:
$padded = Str::padLeft('James', 10);
// And presto! Your new, well-behaved James: ' James' (note those lovely extra spaces)
Happy padding, partner! May your strings always be well-fed and your corrals perfectly full!
Ahoy there, code wranglers! Let’s talk about the Str::padRight() method, a mighty Laravel tool that’ll make your strings as pretty as a pirate’s parrot. Imagine you’ve got a string, let’s call it ‘Captain James’, but it’s feeling lonely and under-lengthy on a page that demands 10 characters minimum - enter the Str::padRight() method!
Here’s how it works:
use Illuminate\Support\Str;
$paddedJames = Str::padRight('Captain James', 10); // Not enough swashbuckling spirit yet...
// 'Captain James--' Now we're talking like a proper pirate!
But wait, there's more! If you want to add some mystery and danger to your string, you can omit the padding character:
$mysteriousJames = Str::padRight('Captain James', 10); // 'Captain ' Mysterious, isn't it?
So there you have it, mates! Now you can fill out those strings like a pro and make your Laravel code shine brighter than Davy Jones’ gold. Happy coding, me hearties!
Ahoy there! Welcome to the pirate’s bounty of secure password generation! Dive into the depths of Laravel with the Str::password() method, a swashbuckler’s secret weapon that crafts ye a cryptographically-secure treasure chest full of letters, numbers, symbols, and even some stray spaces!
By default, this method mints ye a 32-character long password, so you can be sure that it’s enough to make even the most fearsome cyber-sea serpents quake in their digital boots. But if ye feel like ye need something shorter (or longer), just pass in the desired length as an argument:
use Illuminate\Support\Str;
$defaultPassword = Str::password(); // 'EbJo2vE-AS:U,$%_gkrV4n,q~1xy/'
$shorterPassword = Str::password(12); // 'qwuar>#V|i]N'
So ho there! Now ye can navigate the treacherous waters of online security with confidence, knowing that Laravel’s Str::password() method will stand by your side like a faithful parrot, squawking out secure, random passwords with a grin and a swashbuckle!
Ahoy there, code pirates! Steer clear of the ‘ol “one-for-all” conundrum with the delightfully named Str::plural() function! This swashbuckling Laravel method transforms a lonesome word into a hearty group, akin to calling forth a flock of seagulls after a fresh catch.
So if you find yourself in need of turning ‘car’ into ‘cars’, or ‘child’ into ‘children’, this is your treasure map! Just remember, like with all good pirate tales, there’s an extra surprise for the observant amongst ye:
use Illuminate\Support\Str;
$plural = Str::plural('car'); // Bingo! We got us some cars.
$plural = Str::plural('child'); // Hooray! It's children, matey!
But wait! If ye be needing the singular form, just feed it an 'ol 1:
```php
$singular = Str::plural('child', 1); // Aye aye, cap'n! That's one child.
Now, if you be a fancy pirate and yer plunder exceeds a thousand, ye can even prepend the count to your pluralized treasure:
```php
$label = Str::plural('car', 1000, prependCount: true); // Arr! That's 1,000 cars!
Happy pluralizing and remember: it’s better to be a part of a team than the lone ranger on a deserted island, even if ye are a pirate. Arrrr!
Alright, let’s get this party started! 🚀
Str::pluralStudly() {.collection-method} 🤖
Are you tired of manually conjugating your code into a plural frenzy? Worry no more, friends! Introducing the Laravel’s Str::pluralStudly() method – your new best buddy when it comes to turning studly caps singular words into their fabulous plural counterparts!
This function supports a wide variety of languages, just like that polyglot friend you have who always knows the coolest slang.
use Illuminate\Support\Str;
$plural = Str::pluralStudly('VerifiedHuman');
// We're now talking about VerifiedHumans! 🎉👩💼👨💼
$plural = Str::pluralStudly('UserFeedback');
// UserFeedback? More like UserFeedbacks, baby! 😉💬💬
Think of it as having a personal AI-powered grammar nazi on your side. How’s that for power levels?
You can even specify whether you want the singular or plural form by providing an integer as a second argument to the function:
use Illuminate\Support\Str;
$plural = Str::pluralStudly('VerifiedHuman', 2);
// VerifiedHumans it is! Time to get plural with it. 🤹♂️🤹♀️
$singular = Str::pluralStudly('VerifiedHuman', 1);
// Back to the singular life, VerifiedHuman. 😕💔
Remember, with great power comes great responsibility. Use your newfound powers wisely, and may all your code be grammatically correct! 🤓🧑🏫
Ahoy there, coders! Today we’re diving into the depths of Laravel’s Str::position() method, a seafaring navigator for your strings! This trusty tool will help you find where in the seven seas (or your string) a particular substring has made anchor.
Let’s set sail with an example:
use Illuminate\Support\Str;
$location = Str::position('Hello, World!', 'Hello');
// 0 - "Hello" was found right at the starting line! A fine catch indeed!
$location = Str::position('Hello, World!', 'W');
// 7 - Looks like 'W' is lurking a bit further ahead. Now that's a mysterious letter!
If your substring can’t be found in the string, this method will return false. It’s like looking for a pirate named ‘Smith’ and finding none—you come back empty-handed (or sea-chestless).
Happy treasure hunting with Str::position()! Keep it up, mates!
Ahoy there, Laravel mates! Ever found yourself in need of a swashbuckling string that’s as unpredictable as Captain Barbossa himself? Fear not, for I present to thee: Str::random() – the seafaring secret weapon in your PHP arsenal!
This luminous method will conjure up a mystical string of the specified length, using the powerful sorcery known as PHP’s random_bytes function. Give it a whirl with this incantation:
use Illuminate\Support\Str;
$random = Str::random(40); // That be 40 characters, matey!
Now, when you’re on the hunt for some land lubbers to test your pirate wit against, Str::random() might need a bit of deception to keep things fair. Fret not, because this method has a trusty sidekick: createRandomStringsUsing(). Here’s how ye use it:
Str::createRandomStringsUsing(function () {
return 'fake-random-string'; // Aye, the same one every time, just for laughs.
});
But when ye want your ship to sail back to normal after a hearty bout of jestering, Str::createRandomStringsNormally() will set things right as rain:
Str::createRandomStringsNormally(); // Arrgh! Back to business!
So there ye have it – the magical Str::random() method, perfect for crafting strings that’ll leave any landlubber scratchin’ their head and wonderin’ how ye did it. Happy codin’, mateys!
Ahoy there, mateys! Sail the seas of syntax with the mighty Str::remove() – the pirate’s preferred string-scouring tool!
Yarr, this swashbuckling function scrubs your strings clean of undesirable characters or words, just like Blackbeard cleaning his ship’s deck after a wild night.
use Illuminate\Support\Str; // Don't forget to grab your compass and sea chart!
$string = 'Peter Piper picked a peck of pickled peppers.';
$cleanString = Str::remove('e', $string);
// Now you've got yourself a string as smooth as Captain Hook: Ptr Pipr pickd a pck of pickld ppprs.
Avast ye! If you wish to disregard the case while removing, simply pass false as a third argument to the remove() method – just like how Davy Jones wouldn’t care if you called him “Captain” or “Old Man.”
So hoist the Jolly Roger and set sail for cleaner strings with Str::remove()!
Ahoy there, code pirates! Set sail for a thrilling adventure in the vast sea of Laravel’s Str::repeat() method! This be no ordinary function, but rather a treasure chest brimming with repeatable strings! 🏴☠️
Grab yer ropes and hoist anchor, mateys! First things first:
use Illuminate\Support\Str;
Next, grab ye a humble string (let's call it 'a') and store it away for safekeeping:
$string = 'a';
Now, here's where the magic happens - Str::repeat($string, 5)! This function takes your string and multiplies it by the number you provide (in this case, five). And voila! You've just created a string of five 'a's - a veritable sea of 'a's, if ye will.
aaaaa
Aye, so now ye know how to repeat strings like a true Laravel pirate! Keep those strings sailing and stay tuned for more swashbuckling adventures with our trusty Str::repeat() method! Arrrr! 🌴🐫
Ahoy there, shipmates! Steer clear of the ‘boring’ documentation and dive right into the fun with Str::replace(), the seafaring swashbuckler that sets sail across your Laravel strings! 🚢🌊
use Illuminate\Support\Str; // Grab your compass and charts, ye scurvy dogs!
$string = 'Laravel 11.x'; // Set sail for 'Laravel 11.x' land!
$newCourse = Str::replace('11.x', '12.x', $string); // Aye aye, captain! Replace the old coordinates with new ones: '12.x'!
// Now we're cruisin' towards Laravel 12.x!
But hoist the Jolly Roger if you want to hide the ‘pirates’, because replace() also accepts a caseSensitive argument! By default, it be strict as a schoolmarm:
$newCourse = Str::replace(
'php', // Our destination is 'php' land!
'Laravel', // But we're after Laravel!
'PHP Framework for Web Artisans', // This be our treasure chest!
caseSensitive: false // Arrrgh, let's make this a casual chat!
);
// Treasure found! We've landed in Laravel territory!
Yarr! Navigate through your strings with Str::replace(), the sailor’s best mate on your Laravel voyages! 🏴☠️⚓️
Ah, the Str::replaceArray method! A string-transforming superhero that swoops in to save your text from being dull and predictable.
Imagine you’ve got a string like this: “The event will take place between ? and ?” - not exactly riveting, am I right? But fear not, because Str::replaceArray is here!
use Illuminate\Support\Str;
$string = 'The event will take place between ? and ?';
// Now it's time for the transformation
$replaced = Str::replaceArray('?', ['8:30', '9:00'], $string);
// And now, voila! The event will take place between 8:30 and 9:00. Just like that!
This method takes your boring string, grabs the question marks (the least interesting characters since the ampersand), and gives them a makeover by replacing them with some exciting new times. And just like that, you’ve got a spruced-up string ready to impress at your next event!
Ahoy there, coders! Sail with me to the buccaneer’s bounty of text transformations - the mighty Str::replaceFirst() method! This is no ordinary treasure map, but a key to replacing the first pirate in your string’s parrot crew.
Shiver me timbers! Use Illuminate\Support\Str;
Arrr, ye swabby! Replace 'the' with 'a', like so:
$replaced = Str::replaceFirst('the', 'a', 'the quick brown fox jumps over the lazy dog');
Ta-da! The new crew: a quick brown fox jumps over the lazy dog.
Piece of eight, matey! Now you’re ready to set sail for swapping those string scallywags with ease and humor. Yarr, enjoy your adventures in code land!
Ahoy there, code wranglers! Today we’re going to have a jolly good time learning about the Str::replaceLast() method, which is like a reverse Robin Hood for strings. Instead of stealing from the rich and giving to the poor, it replaces the last occurrence of a ‘rich’ value with something ‘poor-er’.
Let’s see this stringy shindig in action:
use Illuminate\Support\Str;
$initial = 'the quick brown fox jumps over the lazy dog'; // Oh, what a tangled web we weave!
// And now, let's give our poor sentence a makeover with Str::replaceLast()!
$replaced = Str::replaceLast('the', 'a', $initial); // Remember, 'the' is out, 'a' is in!
// Our new sentence: the quick brown fox jumps over a lazy dog
In this example, Str::replaceLast() has replaced the last ‘the’ with an ‘a’, leaving us with a sentence that could have been written by Dr. Seuss himself! Now go forth and make your strings dance to your tune. And remember, in the world of coding, change is the only constant! 🤘🏾💃🏽🎶
Ahoy there, matey! Buckle up as we dive into the swashbuckling world of Laravel string manipulation with the Str::replaceMatches() function! This here be no ordinary string replacement method - oh no, it’s a pirate’s treasure chest of pattern-matching goodness!
use Illuminate\Support\Str;
$cleanedSpeak = Str::replaceMatches(
"Arrr pattern: '/[^A-Za-z0-9]++/'",
"Replace with: ''",
"Subject: '(+1) 501-555-1000'"
);
// Treasure's taken shape, matey! '15015551000'
But wait! There be more to replaceMatches() than meets the eye. Yar, it can also accept a closure that will be invoked for each match found in your string. Think of it as a pirate’s helper, aiding ye in crafting custom replacement logic within the closure:
use Illuminate\Support\Str;
$numbersAsBrackets = Str::replaceMatches(
"Pattern: '/\d/'",
function (array $matches) {
return '['.$matches[0].']';
},
"Number to transform: '123'"
);
// Ye'll find numbers neatly wrapped in brackets now, matey! '[1][2][3]'
Now that ye understand Str::replaceMatches(), you can sail off into the sunset with a string as tidy as a ship’s deck after a good scrubbing. Arr matey, happy coding!
Ahoy there, Code Cowboys and Codettes! Let’s dive into the wild west of string manipulation with a trusty sidekick named Str::replaceStart(). This method is as quick on the draw as a gunslinger in a high-noon showdown.
Here’s how it works: imagine you’ve got your trusty old horse, “Hello,” and you want to rename him to “Laravel World.” But the law states that only the first word can change, so “World” stays put. That’s exactly what Str::replaceStart() does!
use Illuminate\Support\Str;
$newSteed = Str::replaceStart('Hello', 'Laravel', 'Hello World'); // Ta-daa! Laravel World it is!
But, hold your horses! If you tried to rename "World" instead, it'd stay the same as before. That's because `Str::replaceStart()` only works its magic on strings that start with the target word:
$newSteed = Str::replaceStart('World', 'Laravel', 'Hello World'); // Sorry pardner, but World remains unchanged!
And there you have it, wrangling words has never been so easy! Keep on coding, partner!
Ahoy there, code pirates! Today we’re gonna swashbuckle our way through the treacherous seas of Laravel string manipulation with the mighty Str::replaceEnd() method. This ain’t your garden variety replace function, no siree! This one’s a sneaky little devil that only changes the last appearance of its target in a string… if it finds it at all!
*Yarr matey!* Use this magic when you want to change "World" to "Laravel" at the end of "Hello World", but leave "Hello World" intact if ye just wanted to replace something else.
$replaced = Str::replaceEnd('World', 'Laravel', 'Hello World'); // Hooray! Now it's "Hello Laravel"!
But be warned, if you try to change the beginning or middle of a sentence with `Str::replaceEnd()`, it'll look at ye cross-eyed and laugh in your face.
$replaced = Str::replaceEnd('Hello', 'Laravel', 'Hello World'); // Alas! The original "Hello World" still stands, and the 'ello' has gone unchanged.
So there ye have it, me hearties! Keep your strings in shipshape with Str::replaceEnd(). It’s a handy tool for when you need to find and replace that elusive last word or letter without causing a mutiny on the Bounty… I mean, in your code. Happy sailing!
Ahoy there, coding pirate! Ever find yourself in a pickle, trying to read Shakespearean scripts backwards for fun? Well, worry no more, because Laravel’s got your back with the Str::reverse() method!
Just like Captain Barbossa commanding “Party up!” (which, if reversed, would sound like our beloved method), this function does a pirate’s delight: it flips strings upside down!
use Illuminate\Support\Str;
$reversedGreeting = Str::reverse('Hello World');
// Out comes "dlroW olleH", a secret message to fellow coders that we've got this reversing lark handled!
So if you ever need to spin words around like a ship in the Bermuda Triangle, Str::reverse() is here to help you navigate the treacherous waters of coding with a smile on your face (and confusion on theirs)! Yarr-ghastly fun!
Ahoy there, coding pirates! Sail the seas of syntax with us as we delve into Laravel’s swashbuckling Str::singular() method. This dashing function is your ticket to transforming a rowdy bunch of scallywags into a single, fearsome foe – or in non-pirate terms, it converts a string into its solitary form!
Hold onto yer hats, mateys, as we set sail on this linguistic voyage. This method supports every tongue that Laravel’s enchanted Pluralizer understands:
Arrr matey, grab thar `Str::singular()`, and see 'em cars become a singularly terrifying 'car'. And watch in amazement as those rowdy 'children' metamorphose into the much more manageable 'child'!
use Illuminate\Support\Str;
Smooth sailing to ye, and may yer coding adventures be filled with laughter and loot!
Ahoy there, shipmates! Buckle up as we dive into the world of Laravel string manipulation with our trusty pirate companion, Str::slug(). This method is akin to a friendly sea shanty that transforms your rough and tumble strings into smooth, swashbuckling URL-friendly slugs.
use Illuminate\Support\Str; // Grab your compass and chart a course!
$slug = Str::slug('Laravel 5 Framework', '-'); // Set sail for 'laravel-5-framework' land!
Now, if you’re in the mood for a more formal voyage (or just fancy snake case), Str::snake() is your new best friend:
$snakey = Str::snake('Laravel5Framework'); // Fair winds and following seas to 'laravel_5_framework'!
And remember, a good sea shanty (or slug) is always more fun when you share it with others:
echo "Our destination is {$slug}!\n"; // "Our destination is laravel-5-framework!" Arr matey, we made it!
Ahoy there, code wranglers! Saddle up for a wild ride through the wacky world of Laravel string transformation, starting with our trusty steed: Str::snake(). This ain’t your garden-variety horse, but rather a magical unicorn that converts your strings into the mystical land of ‘snake_case’.
use Illuminate\Support\Str;
$transformed = Str::snake('fooBar');
// Out trots our new friend: foo_bar
But wait, there's more! If you fancy a dash of distinction in your 'snake_case', just add a little extra command to your reins:
```php
$transformed = Str::snake('fooBar', '-');
// And behold: foo-bar, the black sheep of the snake family.
Now, wasn’t that a delightful jaunt? Let’s move on to greener pastures and continue this equestrian escapade!
Ahoy there, shipmates! Let’s hoist the sail of enlightenment with a hearty dose of Laravel fun and learnin’! Today’s port of call: Str::squish(), the pirate’s best friend in string trimmin’!
Ye see, when ye got a string like “laravel framework”, it ain’t just the wind that’s blowing between those words. The ghost of old Captain WhiteSpace has been haunting your code, making it look ragged and uncanny. No fear, Matey! Str::squish() is here to save the day!
use Illuminate\Support\Str;
$string = Str::squish(' laravel framework ');
// laravel framework (with a clean bill of health)
So, when ye need to squeeze out the extra space and make your code shine like a freshly polished pirate ship, just holler for good ol’ Str::squish(). Happy codin’, mateys! And remember: “A well-trimmed string is a happy string!” (Arrr!)
Ahoy there, coders! Let’s take a jolly journey into the wonderful world of Laravel string manipulation with our trusty sidekick, Str::start()! This method is like that charming barista who always adds a dash of flavor to your coffee – but in this case, it’s a single sprinkle of your chosen value onto your string.
But here’s the twist: It only does its magic if your string isn’t already sporting that particular value at the beginning! Kinda like a shy wallflower at a ball who will only dance once asked.
use Illuminate\Support\Str;
// Poor "this/string" was left hanging without a slash, let's fix that:
$fixed = Str::start('this/string', '/');
// /this/string – all better!
Now, let's say you already added the prefix to your string but for some reason, you feel like it's missing something:
$already_started = '/this/string';
Str::start($already_started, '/');
// /this/string – still the same ol' string!
Just remember that this method will only work if you provide a single character or symbol as your prefix. It’s like inviting just one guest to your party; any more than that, and it gets confusing!
Happy coding, and may all your strings start with style! 🎉🎈
Ahoy there, matey! Let’s dive into the swashbuckling world of Laravel strings with the Str::startsWith() method - a real treasure for your code piracy adventures!
Now, if you’ve ever found yourself wondering whether Jack Sparrow’s beard matches the beginning of a certain phrase, fear not! This trusty companion will help you find out:
use Illuminate\Support\Str;
$beardMatch = Str::startsWith('This is my name', 'This'); // True, Captain Jack's beard fits just fine!
But what if ye be a scurvy dog with indecisive tastes? No worries! If you present the method an array of possible values, it’ll return true as soon as it finds a match:
$piratePossibilities = ['This', 'That', 'There'];
$beardMatch = Str::startsWith('This is my name', $piratePossibilities); // True, Jack Sparrow's beard matches one of the possibilities!
So hoist the Jolly Roger and let your strings start with a bang – with Str::startsWith(), you’ll never set sail without knowing who’s leading the charge! Arr matey!
Ahoy there, code pirate! Ever find yourself drowning in a sea of snake_case? Fear not, me hearty! Laravel’s Str::studly method is here to save the day! This nifty function will transform your string into the majestic StudlyCase, making it as grand as a ship’s name on the high seas.
Use yer trusty compass, matey! Import Illuminate\Support\Str first:
use Illuminate\Support\Str;
Now, hoist the Jolly Roger and point it at that poor, neglected string 'foo_bar'. With a single call to `Str::studly`, you'll transform it into the elegant FooBar that it deserves to be!
$converted = Str::studly('foo_bar');
Arr matey, that’s just swashbuckling programming at its finest! Happy coding, and may your code always be as clear as a sunny day on the open ocean!
Ahoy there! Sailors of the PHP seas! Fancy a dive into the depths of Laravel’s string manipulation? Brace yourself for the captivating Str::substr() method, the nautical navigator of your code! 🌴🐬
This isn’t just any ordinary compass, but a trusty tool that helps you sail through strings. You provide it with two crucial coordinates - the start (port or starboard?) and length (number of cannons, maybe?), and voila! It returns the section of your string that lies between those points. 🌈
For instance, if you’re curious to find out what the Laravel in “The Laravel Framework” is called, just issue the following command:
use Illuminate\Support\Str;
$shipName = Str::substr('The Laravel Framework', 4, 7);
// Laravel (yarr!)
So, set sail on this method, and watch your code become as smooth as a pirate’s parrot! 🦜⚓️
Ahoy there, Laravel pirates! Get ready to set sail on the seas of strings with the Str::substrCount() method - a swashbuckling helper that’ll help you count the number of occurrences of a certain phrase in your favorite sea shanty (or any ol’ string for that matter).
Here’s an example to get you hooked:
use Illuminate\Support\Str;
$count = Str::substrCount('Yo ho, yo ho, a pirate's life for me, but I prefer ice cream over grog.', 'life');
// 3 (arrgghhh!)
See what I did there? We counted the number of times “life” appears in our not-so-traditional sea shanty. This method is an excellent way to keep tabs on those pesky words that seem to show up more often than ye might expect! Happy coding, mateys!
Ahoy there, code wranglers! Ever found yourself in a pickle trying to replace some text within a string like a cat’s trying to catch a laser pointer? Well, fear not, for the mighty Str::substrReplace() method is here to save your day!
This Laravel superhero darts into action, scouring your string (let’s call it Stranger Things) from the position you specify with the third argument (think of it as a pirate’s ‘shiver me timbers’ mark), and zaps the text it finds there with a new one, all thanks to the fourth argument!
use Illuminate\Support\Str;
$result = Str::substrReplace('1300', ':', 2);
// 13: (Poof! The '0' magically disappeared)
$result = Str::substrReplace('1300', ':', 2, 0);
// 13:00 (Zap! A new '00' appeared out of nowhere)
Now, if you fancy inserting a new string without touching the existing characters in your Stranger Things, simply pass 0 as the fourth argument! Pirate-speak not your thing? No worries, here’s another analogy: think of it as replacing the middle letters in ‘kitten’ with ‘dog’, but only if you want to get ‘kidog’.
So there you have it, folks! The Str::substrReplace() method – your new best friend when string manipulation gets hairy. Happy coding! 🚀🎉🎊
Ahoy there, code wranglers! Prepare to embark on a linguistic journey with the Str::swap method - it’s like a culinary translation service for your strings!
This magical function, straight out of our favorite PHP enchanted book, works its wonders using the venerable strtr spell:
use Illuminate\Support\Str;
$wordSalad = Str::swap([
'Tacos' => 'Burritos', // Say adios to those tacos!
'great' => 'fantastic', // Time to level up the compliments, matey!
], 'Tacos are great!'); // A simple sentence that's about to get a flavorful makeover!
// And voila! Out pops: Burritos are fantastic!
So if you ever find yourself in a pickle where you need a change of words, fear not, for the Str::swap is here to lend a hand and turn your strings into something far more appetizing!
Oh, let’s dive into the magical world of Laravel strings where the Str::take() method is our trusty sidekick!
Imagine you’re at a party filled with chatty people and you just want to hear the first five songs. No problemo! With Str::take(), you can snatch the initial five letters from your favorite motivational phrase, “Build something amazing!” Just like that, it’s transformed into “Build” - perfect for those late-night dance-offs!
use Illuminate\Support\Str;
$taken = Str::take('Build something amazing!', 5);
// And now you're ready to boogie down!
Remember, just like at the party when you need to switch from a salsa to a cha-cha, Str::take() helps you grab different parts of strings with ease. Happy string dancing! 💃🏽🕺🏼
Ahoy there, code cowboys and codettes! Saddle up for a jolly journey into the wild west of string manipulation with the trusty Str::title method – your friendly neighborhood lasso for transforming strings into proper title case cowpokes!
So buckle up, partner! Here’s how to rope this baby in:
use Illuminate\Support\Str; // Import the Str class like you're inviting an old friend to a hoedown
$newTitle = Str::title('a nice title uses the correct case'); // Pass your string along and watch it magically transform!
// A Nice Title Uses The Correct Case
Now, wasn’t that easier than trying to herd cats in a tornado? Happy trail-blazing with Str::title, y’all!
Ahoy there, coding pirates! Hoist the sails and prepare to embark on a thrilling journey with Laravel’s Str::toBase64() method!
This magical function transforms your string into the lost language of Base64 – yes, you heard it right, mateys! The sea shanty goes like this:
use Illuminate\Support\Str;
$base64EncodedLaravel = Str::toBase64('Laravel');
// And the result will look something like TGFyYXZlbA==. Swabbie, take a gander!
Wondering what this cryptic string could mean? Don’t worry, mate – it translates to our common tongue as ‘Laravel.’ Fancy that, eh? So next time you find yourself in need of some secret messaging with your pals on the high seas (or just working on a Laravel project), give this method a try!
Arrrrr-ighty then! Set sail for Base64 land and discover the fun side of coding! 🌴⛵️🐘
Ahoy there, coding pirates! Fancy a yarn about Str::transliterate(), the method that’s as nimble as a ship in a squall and just as essential?
Welcome to the ASCII shanty town! This swashbuckling string manipulator is here to help you convert your wild, foreign-looking characters into something more palatable for ol’ Clunky Computer.
Just like Captain Cook exploring unknown territories, Str::transliterate sets sail on a voyage to transform your string:
use Illuminate\Support\Str;
$email = Str::transliterate('ⓣⓔⓢⓣ@ⓛⓐⓡⓐⓥⓔⓛ.ⓒⓞⓜ');
// '[email protected]' - Ta-da! Pirate talk to English, in a flash!
So, hoist the Jolly Roger high and embrace the sea of symbols with Str::transliterate at your side!
Alright, alright, let’s get this party started! Welcome to the whirlwind world of Laravel string manipulation with a delightful dash of humor. Today, we’re gonna talk about the Str::trim() method - your new best friend when it comes to stripping away those pesky whitespace characters (and their exotic Unicode cousins) from the beginning and end of your strings.
Imagine you’re at a fancy ballroom dance party, and there are these annoying string “partners” clinging onto you from all sides with their excessive white space and Unicode friends. Well, Str::trim() is like that charming gent who sweeps in, scoops them up, and sends them packing without causing a scene!
use Illuminate\Support\Str;
$string = Str::trim(' foo bar ');
// Translates to:
// "Hey there, white space and Unicode pals! It's time for you to hit the exit!"
// And now, voila! Our clean-cut 'foo bar' is left standing tall and proud.
So next time you find yourself in a pickle with unwanted string embellishments, just call upon the help of Str::trim(). It’s the dance partner you didn’t know you needed until now!
Ahoy there, intrepid Laravel devs! Today we’re diving into the delightful waters of the Str::ltrim() method - a veritable lifebuoy for your string woes! Now, don’t let that fancy name fool you; it might sound like something straight out of a sci-fi novel, but fear not! It’s just a simple function to trim off those pesky whitespaces (and other characters) at the start of your string.
But wait, there’s more! Unlike its PHP counterpart, our trusty Str::ltrim() is no one-trick pony; it’ll also happily remove those pesky unicode whitespace characters that give even the best of us a headache. So if you find yourself dealing with strings that look like they were dipped in marshmallow fluff, fear not! Our trusty Laravel companion is here to help!
use Illuminate\Support\Str;
$string = Str::ltrim(' foo bar ');
// 'foo bar ' - Yay! No more pesky whitespaces at the start!
So there you have it, a little tidbit of Laravel knowledge that’ll make your life just a teensy bit easier. Happy coding, and remember: in a world filled with string chaos, the Str::ltrim() method is like finding a needle in a haystack… except instead of a needle, you find a perfectly trimmed string!
Ahoy there, fellow code pirates! Let’s hoist the sails of knowledge and dive into Laravel’s swashbuckling Str::rtrim() method - the deck-clearing, bilge-rat-banishing, scurvy-freeing tool every seafaring coder needs!
If you find yourself stuck with a string that looks like it’s been caught in a hurricane (you know, spaces at both ends), fear not! This trusty method will trim those pesky whitespaces (or other characters) from the end of your string like a well-timed cannonball to a pirate ship!
use Illuminate\Support\Str;
$shipshapeString = Str::rtrim(' foo bar '); // 'foo bar' - ta-daaah!
Unlike the native PHP rtrim function, our Laravel comrade plays by the rules of the high seas. It’s not just about space, it’s about Unicode whitespace characters too, so you can keep your strings clean and crisp without worrying about hidden characters lurking below deck! Arr matey!
Ahoy there, coder matey! Ever find yerself in a pickle with an unruly string that needed a bit o’ refinement? Look no further than the good ship Str::ucfirst()! This trusty method will hoist the anchor on your string and return it with a swanky capitalized first character, ready to set sail in style:
Shiver me timbers! Use Illuminate\Support\Str;
$string = Str::ucfirst('foo bar');
// "Foo bar" - a much tidier ship, wouldn't ya say?
Yarr, matey! Now yer string is as sharp and polished as Captain Jack Sparrow’s cutlass. Keep that code sailing smooth and your crew happy with the help of Laravel’s pirate-approved Str::ucfirst() method!
Ahoy there, coders! Ever find yourself in a pickle trying to split a string by uppercase characters like it’s the last anchor on the Titanic? Fear not, for Str::ucsplit() is here to save your day! This dazzling Laravel method is as slick as a greased eel and just as essential in a good ship’s kitchen.
Here’s an example that’ll make even the saltiest seadog grin:
use Illuminate\Support\Str;
$treasureMap = Str::ucsplit('FooBar');
// [0 => 'Foo', 1 => 'Bar']
With Str::ucsplit(), you can easily navigate the choppy waters of string manipulation, without a compass or a sextant! So go forth and conquer those strings like a modern-day Captain Jack Sparrow. Arr matey!
Ahoy there, matey! Prepare to embark on a linguistic adventure with the Str::ucwords() method - where the first letters of your words are transformed into bold and proud capital letters, like the opening salvo in a pirate’s battle cry! 🏴🌈
use Illuminate\Support\Str;
$string = Str::ucwords('laravel framework');
// "Laravel Framework" - now you can talk like a proper pirate (or just someone with good manners)! 😉
Remember, ye scurvy dogs, this method only affects the first letter of each word, leaving your shipmates’ names and favorite parrot unscathed. So beware of using it on private messages to avoid any confusion or laughter among friends! 😜🐵
Happy coding, swashbucklers! May your code be clear as a crystal sea map and as powerful as the Poseidon’s trident! ⚓️🌊
Ahoy there, coders! Let’s embark on a whimsical journey through the vast seas of PHP with Laravel’s trusty vessel, Str::upper(). Think of it as a pirate who’s had one too many grog and is now shouting every letter of your string at the top of his lungs.
Grab yer autoloader, mateys!
use Illuminate\Support\Str;
Capture yer string like ye would a mermaid:
$string = Str::upper('laravel');
And behold, as if by the magic of a wish-granting fish, ye'll find yerself with LARAVEL in yer hands!
This method is not just a simple capitalization, but a full-blown transformation into the realm of shouty Internet speak. Now isn’t that swashbucklingly fun? Happy coding! 🏴☠️
Ahoy there! Steer clear of mundane IDs and hoist the sail of uniqueness with the Str::ulid() method, a seafarer’s delight in Laravel’s nautical navigation tools! This command mints ULIDs (Universally Loved Identifiers), a compact, chronologically-sorted, uniquely distinctive anchor you can drop anywhere in your code ocean.
use Illuminate\Support\Str;
return (string) Str::ulid(); // Sails away with a treasure trove of 01gd6r360bp37zj17nxb55yv40, arrgh!
Feeling curious about when the ULID was forged? Fret not! Laravel’s Carbon integration will gladly serve you a date-and-time snack using the createFromId method:
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
$date = Carbon::createFromId((string) Str::ulid()); // Slices and dices your ULID, serving up a yummy date!
In the realm of pirate tests, you may want to fake a ULID instead of serving the real deal. createUlidsUsing is your trusty compass in these waters:
use Symfony\Component\Uid\Ulid;
Str::createUlidsUsing(function () {
return new Ulid('01HRDBNHHCKNW2AK4Z29SN82T9'); // Swab the deck with your own ULID, matey!
});
When you’re ready to resume normal operations in the high seas, call upon createUlidsNormally:
Str::createUlidsNormally(); // Hoist the Jolly Roger and set sail with proper ULIDs once more!
So there ye have it, matey! Master the art of creating and managing ULIDs with the Str::ulid() method in Laravel – your code will never feel like a shipwreck again! 🌴🌺⚓️
Ahoy there, coding pirates! Steer your ships towards the shores of Laravel’s Str treasury, where we’ve anchored the Str::unwrap() method – a swashbuckling tool to slay those pesky string prefixes and suffixes that have taken over your code like seagulls on a fresh loaf of bread!
use Illuminate\Support\Str; // Import Str, we can't stress this enough (pun intended)
Str::unwrap('-Laravel-', '-'); // Remove the minus signs on both sides of "Laravel" – perfect for those who don't like negative thoughts!
// Laravel, a much happier string!
Str::unwrap('{framework: "Laravel"}', '{', '}'); // Grab the "framework: 'Laravel'" and toss out the curly braces – now that's some neat JSON parsing!
So hoist the Jolly Roger, ye mateys! With Str::unwrap(), you can sail through your code like a well-oiled ship, leaving unwanted strings in the wake of your coding prowess. Arr matey, fair winds and good luck! 🌬️⚓️🎉
Alrighty, buckle up, because we’re about to dive into the world of UUIDs! The Str::uuid() method is Laravel’s very own seashell to the universe of unique identifiers (v4, to be precise). It’s like a virtual fishin’ trip, but instead of catching fish, you’re reeling in one-of-a-kind identifiers that’ll make your database feel like an exclusive VIP lounge.
Here’s the code to cast your line:
use Illuminate\Support\Str; // Import Str, our trusty fishing rod
return (string) Str::uuid(); // Cast your line and wait for that UUID to bite!
Now, during the testing phase (when you’re pretending to be a shark among minnows), it’s sometimes handy to serve up a pre-prepared UUID instead of catching them live. That’s where the createUuidsUsing method comes in:
use Ramsey\Uuid\Uuid; // Import Uuid, our secret bait recipe
Str::createUuidsUsing(function () {
return Uuid::fromString('eadbfeac-5258-45c2-bab7-ccb9b5ef74f9'); // Cast your line with our secret bait!
});
Finally, to ensure that uuid() goes back to the traditional UUID fishing after the testing phase (when you’re no longer pretending to be a shark, but back to being human), simply invoke the createUuidsNormally method:
Str::createUuidsNormally(); // And now we're back to catching UUIDs like normal folks again!
And that, my dear Laravel anglers, is how you catch UUIDs with the Str::uuid() method! Happy fishing!
Ahoy there, shipmates! Let’s dive into the nautical depths of Laravel’s UUID generation with Str::uuid7(). This method, akin to Captain Jack Sparrow finding buried treasure, unearths a Universal Unique Identifier (version 7). Just remember, unlike Jack’s compass, this one never points towards Tortuga!
Here’s how you can use it:
use Illuminate\Support\Str;
$uuid = Str::uuid7(); // Get a new UUID like an undiscovered island in the vast sea of data
echo $uuid;
Now, if you fancy generating an ordered UUID, pass a DateTimeInterface as an optional parameter:
use Illuminate\Support\Str;
use DateTimeInterface;
$now = new \DateTimeImmutable('now', new \DateTimeZone('UTC')); // Ensure timezone consistency, pirates love their clocks!
$orderedUuid = Str::uuid7(time: $now); // Sail through the sea of time, generating an ordered UUID like a compass guiding the way!
echo $orderedUuid;
So there you have it, matey! Laravel’s Str::uuid7() – your go-to companion for exploring the mystical waters of unique identifiers in your application. Now, let’s hoist the sails and sail into the sunset of better coding practices!
Ahoy there, coding cowboys and codettes! Set sail with me on a journey through the treacherous seas of Laravel documentation - or at least, a journey to Str::wordCount(). This isn’t your ordinary pirate adventure, but rather an exciting excursion into word counting, with our trusty companion, good old Str!
Hook up yer lasso and ride along:
use Illuminate\Support\Str;
Now, let us embark on a voyage filled with words! (No mermaids or sea monsters here, sorry!)
Str::wordCount('Hello, world!'); // Brace yourself for the count: 2 - Aye, two lively words we've got there!
Remember, with Laravel at your helm and Str by your side, you’ll never be lost at sea of text again. Happy sailing!
Ahoy there! Buckle up, coding cowboys and codettes! Today’s lesson is all about taming those unruly strings with the mighty Str::wordWrap() method - a lasso for your words that ensures they never gallop off into the sunset without your say-so.
Let’s saddle up and ride into this:
use Illuminate\Support\Str;
$text = "The quick brown fox jumped over the lazy dog.";
// Swap those long words for short ones (or just plain breaks)!
Str::wordWrap($text, characters: 20, break: "<br />\n");
/*
Hold your horses! Here's what you get:
The quick brown fox<br />
jumped over the lazy<br />
dog.
*/
See? Now we’ve got a beautifully formatted string, cowpoke style. So keep wrangling those strings with Str::wordWrap(), and happy coding days to y’all! 🤠🚀
Ahoy there, coding pirates! Step right up to the Str-tacular show where we unveil the swashbuckling Str::words() method! This cunning technique helps ye limit the number of words in yer string, like a parrot squawking only three phrases before it starts repeating itself.
Wanna know how to use this marvel? Here be the code:
use Illuminate\Support\Str; // Import the magic class
return Str::words('Perfectly balanced, as all things should be.', 3, ' >>>'); // Three phrases and a piratey appendage for good measure!
// And lo and behold, ye get: Perfectly balanced, as >>>
Avast, me hearties! Master this method and yer strings will never be too long to fit in the ol’ parchment again! Arr matey!
Ahoy there, code sailors! Sail the Laravel seas with the Str::wrap() method – a trusty shipmate that’ll help you spruce up your strings with style and flair!
Just like wrapping presents on Christmas morning or the codfish in salt before they hit the frying pan, Str::wrap() can take your humble string and swaddle it in an extra layer of another string or even a pair of them.
use Illuminate\Support\Str;
// Wrap 'Laravel' in double quotes like a juicy steak ready for barbecue
Str::wrap('Laravel', '"');
// Output: "Laravel" (Just like your favorite song, but without the music)
// Wrap 'is' with 'This' before and ' Laravel!' after, creating a clever sentence fit for Shakespeare himself!
Str::wrap('is', ['before' => 'This ', 'after' => ' Laravel!']);
// Output: This is Laravel! (Methinks the string does protest too much!)
Remember, in the world of Laravel, Str::wrap() won’t warp your strings in unwanted ways or leave them limp and soggy like overcooked spaghetti. Instead, it’ll make sure they’re properly coated with the flavors you desire!
Ahoy there, matey! Buckle up as we delve into the swashbuckling world of Laravel string manipulation with the str() function!
Picture this: You’re a pirate captain in need of a proper introduction. Enter str() - your new best friend who turns simple strings like “Taylor” into grand introductions such as “Taylor Otwell”, without you having to splice the words together yourself! It’s like having Grog the First Mate do all the heavy lifting for you.
$intro = str('Taylor')->append(' Otwell');
// 'Taylor Otwell' - just like that, yarr!
But that’s not all, me hearties! If ye leave str() high and dry without a string to play with, it’ll conjure up an instance of Illuminate\Support\Str all on its own. Imagine it as a friendly barkeep who always has a clever quip ready when you need it most.
$snake = str()->snake('FooBar');
// 'foo_bar' - perfect for those tricky snake-infested caves!
So there ye have it, mateys! The str() function - your swiss army knife of string manipulation in the vast seas of Laravel! Now go forth and conquer those strings like a true pirate captain! Arrrr!
Ahoy there, coders! 🚢 Let’s sail through some Laravel goodness with the trans() function, a swashbuckling translator for your messages!
Think of it as a trusty old pirate parsing your translation keys from your treasure trove of language files 🏛️:
echo trans('messages.welcome'); // Yarr, speak the language!
Now, if your desired translation key happens to walk the plank, fear not! trans() will kindly return the key itself instead of a sea monster. So, in our swashbuckling example above, you’d get messages.welcome if the key wasn’t found.
But wait! There’s more! With the transChoice() method, you can turn plural numbers into proper pirate-speak:
echo trans_choice('messages.loot', 2, ['gold coins', 'chests of treasure']); // "2 gold coins" or "2 chests of treasure"
So, remember, when you need to communicate like a true captain of the seven seas, reach for the trans() and transChoice() functions! Arrrr, matey! 🐘🎉🏴☠️
Ahoy there, coding cowboys and cybernauts! Let’s dive into the Wild West of Laravel localization with a trusty ol’ pal named trans_choice(). This ain’t no common outlaw; it’s a function that translates your chosen translation key with an added touch of inflection.
echo trans_choice('messages.notifications', $unreadCount);
Now, what exactly is this mysterious $unreadCount? Well, buckle up partner! It’s the number of unread messages in your digital saloon (a.k.a. app). Just like a gold nugget, it gives you the count of notifications!
But worry ye not if that there translation key ain’t sitting pretty in yer saddlebag! trans_choice() is a stand-up guy who’ll return the key if its translation has gone missing. So, using our example, ol’ trans_choice() would holler back “messages.notifications” if it couldn’t find a suitable translation for your key.
So there you have it! A friendly reminder that with friends like trans_choice(), you don’t need enemies in the land of Laravel localization. Yee-haw!
Oh, Fluent Strings! Your friendly neighborhood syntax superheroes, here to save the day from cumbersome, caped-crusader-esque string manipulations. With these bad boys in your toolbelt, you can string together a symphony of operations like it’s a string orchestra performing a Bollywood blockbuster! 🎶🎺
Let’s say you want to append something after another, but you don’t feel like breaking into a sweat with traditional string concatenation. Fret not, dear user! Fluent Strings have got your back! Here’s how:
$str = "Hello";
$afterStr = "World!";
$fluentStr = app('Illuminate\Support\Fluent');
// Using fluent strings
$combined = $fluentStr->create($str)->after($afterStr);
echo $combined; // Outputs: HelloWorld!
You can see that by using Fluent Strings, we’ve managed to make the process of appending a string more readable and less… spandex-y. Now go forth and conquer your coding challenges with these stringly superpowers! 🚀💪🚀
Ahoy there, code swashbucklers! Sail with me to the enchanted waters of Laravel String Navigation, where we’ll learn about the swashbuckling after method!
Yarr matey, prepare your compasses for a journey to find hidden treasure in strings! This magical method returns everything after the pirate-approved value you specify. If said value doesn’t exist, fear not! The entire string will be returned like a chest filled with doubloons:
Arrrgh! Use yon Str class:
Str::of('This is me hearty name')->after('This is') ye shall find...
' my hearty name'
Now, let’s hoist the anchor and set sail for more Laravel adventures!
Ah, the afterLast method! It’s like a magic wand for string splitting but in a very Laravel way. You see, it’s not just about finding the last occurrence of a certain value in a string - it’s about making sure you leave no string unturned!
use Illuminate\Support\Str;
$leftovers = Str::of('App\Http\Controllers\Controller')->afterLast('\\');
// 'Controller', because who needs the whole controller namespace when you're just a humble view?
In case you’re wondering, our beloved afterLast is quite the picky one. It will only give you what comes after the last occurrence of your specified value in the string. If that value doesn’t exist within the string, well… it’s just going to serve up the entire string with a side of “sorry, no leftovers today”.
Hope this helps! Happy coding, and remember: when in doubt, use Laravel! 🚀🌟
Oh, the apa method! It’s like a grammar ninja, but instead of sneaking around in the shadows, it’s just chilling in your Laravel code. This little powerhouse takes a string and transforms it into a regal Title Case champ, following the rules set by the all-knowing APA Style Police.
use Illuminate\Support\Str;
$transformed = Str::of('a nice title uses the wrong case')->apa();
// A Nice Title Uses the Correct Case! ...or else the APA Style Police will be knocking on your door with a sternly worded letter.
Don’t let the APA Style Police break down your doors and ruin your day! Let the apa method do all the heavy lifting for you. It’s like having a personal grammar tutor, but without the awkward silences or pop quizzes.
Ahoy there, code pirates! Sail the seas of Laravel with me as we delve into the swashbuckling world of strings. Today, we’re gonna talk about a method that is not only as exciting as a treasure map but also as essential as your trusty cutlass – the append method!
use Illuminate\Support\Str;
$string = Str::of('Taylor')->append(' Otwell');
// 'Taylor Otwell' – Aye, matey! Our humble "Taylor" now sports a fancy new companion, and together they form a harmonious duo!
Just like adding a parrot to your shoulder or a Jolly Roger to your ship, append lets you add values to your string with ease. So hoist the main sail and set course for a smoother coding experience! 🌴🐘⚓️
Ahoy there, code wranglers! Let’s sail into the world of Laravel strings and have a jolly good time with the ascii method! This nifty little function is like a translator at the United Nations of keyboards - it attempts to convert your string into ASCII values.
So, if you find yourself in a pickle with a non-ASCII character (let’s call them international keyboard rogues), don’t fret! Just grab this life preserver:
use Illuminate\Support\Str;
$mischievousCharacter = Str::of('ü'); // The rogue in question
$asciiTranslator = $mischievousCharacter->ascii(); // Our trusty translator at work
// 'u' - ASCII peace has been restored!
This is the perfect companion for any cross-keyboard communication! So, let’s keep this party going – after all, coding should be as fun as an impromptu pirate dance on a galleon!
Ahoy there, code pirates! Sail the Laravel seas and navigate through directories with the basename method - a swashbuckling tool to grab the final bit of your stringy treasure maps! 🏴☠️
Use the power of Str, ye mateys:
$string = Str::of('/foo/bar/baz')->basename();
// Hoist 'baz' above deck!
If you've got a pesky extension in your path, it's time to toss that anchor:
$string = Str::of('/foo/bar/baz.jpg')->basename('.jpg');
// Arrrr! Now we've got just 'baz', matey!
Ahoy and good luck on your adventure! Don’t forget to bring enough rum for everyone… and a spare lifeboat! 🐬
Alright, coding buddies! Let’s dive into the Laravel universe and discover the magical before method. This method is like a time machine for your strings, sending you back in time to the moment before a specific word appears. It’s perfect for when you need to travel through text without leaving your keyboard!
use Illuminate\Support\Str;
$leftovers = Str::of('This is my name')->before('my name');
// 'This is '
In this example, we’re telling Laravel to transport us back in time before the word “my name” was uttered. And just like that, we find ourselves with a string full of leftovers: ‘This is ’. Now isn’t that a fun way to journey through strings? Happy coding! 🚀🌐💻
Ahoy there, coding sailors! Prepare to navigate the choppy seas of string manipulation with the beforeLast method – a trusty companion on your voyage to PHP nautical dominance! 🌈
Anchor yourself and grab your compass, because we’re about to set sail for an exciting adventure. The beforeLast method is like a trustworthy deckhand who helps you get the right portion of a string before the last occurrence of a specific value.
*hoist anchor!* Use Illuminate\Support\Str and call on the helpful `beforeLast` method to find out what's what:
```bash
$slice = Str::of('This is my name')->beforeLast('is');
// Yo ho ho! You'll find yourself with 'This ', a tidy little bit that keeps your code neat as a pirate's parrot. 🦜
Keep those decks cleared and sails trimmed, as we chart a course for more Laravel lore and seafaring success!
Ahoy there, matey! Prepare to sail the seas of Laravel strings with the between method! This dashing little number’s role is to nab a portion of your string like a pirate plundering treasure. Here’s a swashbuckling example:
use Illuminate\Support\Str;
$loot = Str::of('Shiver me timbers, I be Captain Longbeard!'); // Our string
$treasure = Str::between($loot, 'I', '!'); // ' be Captain' - Find the booty between 'I' and '!'
Arrr, it’s as easy as that! This method will return only the part of your string that lies between two given values. So remember: when you need to separate the wheat from the chaff or pluck a juicy pearl from a sea of text, the between method’s here to help! 🐻🚀🔥🏴☠️
Ahoy there, code pirates! Sail the seas of PHP with Laravel’s enchanting betweenFirst method! This magical spell casts upon a string, separating it like a shark divides its prey – but without any bloodshed, I assure you. 😉
Here’s an example to set your compass straight:
use Illuminate\Support\Str;
$treasureMap = Str::of('[a] bc [d]'); // Our glorious string (or maybe just a map?)
$firstPieceOf88GoldCoins = $treasureMap->betweenFirst('[', ']'); // This will yield "a" – the first gold coin in our stash! 💴🌟
And there you have it, matey! The smallest possible portion of your string is now safely in your treasure chest. Happy coding and remember to keep those seas of code calm and breezy! 🎉
Ahoy there, code pirates! Let’s dive into the treacherous waters of camelCase with our trusty Laravel sidekick – Str!
“Arr matey,” you might be thinking, “I got a barrel full of underscores in me string. How do I make it walk the plank and become a landlubber?”
Fear not, scurvy dogs! The camel method is just the parrot you need to transform that unwieldy, seafaring creature into a respectable camelCase citizen.
Here’s how ye can use it:
use Illuminate\Support\Str;
$newString = Str::of('foo_bar')->camel();
// 'fooBar', as happy as a clam at high tide!
Just call upon the mighty Str, pass in yer string, and let loose the wrath of camelCase upon it. With that, you’ve transformed a motley crew into a well-groomed company, ready to take on any landlubber language out there! Yarrr!
Alright, let’s dive into the enchanting world of Laravel strings! Today we’re talking about the charAt method, a magical spell that lets you pluck a single character from your string cauldron. This isn’t Hogwarts Potions class, but trust us, it’s just as enchanting!
use Illuminate\Support\Str;
$potionsIngredient = Str::of('This is my name.'); // We've brewed a potion, folks!
$sixthLetter = $potionsIngredient->charAt(6); // Oh, look! It's 's'. Could it be our secret ingredient?
Just remember, if you try to peek at an index that doesn’t exist, the method will just shrug its shoulders and return a big fat ‘false’, leaving you with more questions than answers. So keep those indices within bounds, won’t ya? Happy string-weaving! 🧙♂️
Ahoy there, code swashbucklers! Let’s dive into the nautical depths of Laravel’s Str class, shall we? Specifically, we’re talking about the classBasename method - a seafaring navigator that helps you find your bearings in the vast ocean of classes.
This trusty method sails through the treacherous waters of class namespaces, leaving behind all those pesky backyard crabs, and emerges with nothing but the purest class basename! 🐜🌴🏖️
Here’s a little example to steer you in the right direction:
use Illuminate\Support\Str;
$class = Str::of('Foo\Bar\Baz')->classBasename();
// 'Baz', because, let's face it, even pirates don't need their full name on a treasure map! 🏴☠️
So, next time you’re lost in the tangled web of namespaces, remember to hoist the Jolly Roger (Str class) and set sail for classBasename island – your piratey pathway to clarity! 🎉🌴🐠🚀
Alright, buckle up, coding cowboys and codelettes! Let’s dive into the thrilling world of Laravel’s chopStart method - it’s like a magic trick for your strings!
Imagine you’ve got yourself a URL as long as Elon Musk’s Tesla Roadster in space, wrapped around your finger like a digital boa constrictor:
$url = "https://laravel.com";
Now, if you’re tired of having “https://” clinging onto your URL like a hangover on New Year’s Day, fear not! Our trusty chopStart method is here to save the day:
use Illuminate\Support\Str;
$url = Str::of($url)->chopStart('https://'); // And just like that, "laravel.com" appears before your very eyes!
But wait, there’s more! Ever found yourself with a URL starting with both http:// and https://, like a digital Janus of the web? No worries, our heroic chopStart can handle arrays:
use Illuminate\Support\Str;
$url = Str::of($url)->chopStart(['http://', 'https://']); // And just like that, "laravel.com" is free at last!
So there you have it, my friends! With Laravel’s chopStart, you can remove the unwanted from your URLs as quickly and effortlessly as a cat removing its fur after a long nap. Happy coding, y’all!
Alright, code cowboys and codettes! Buckle up, because we’re about to embark on a wild ride with the Laravel chopEnd method, the lasso that wrangles those pesky trailing characters, much like Roy Rogers handling his trusty steed Trigger!
use Illuminate\Support\Str;
$url = Str::of('https://laravel.com')->lasso('.com'); // You heard that right, we're lassoing dot-com here!
// 'https://laravel'
Wanna lasso more than one character? No problemo! Just rope in an array:
use Illuminate\Support\Str;
$url = Str::of('http://laravel.com')->lasso(['.com', '.io']);
// 'http://laravel'
Now, don’t go wrangling strings without a lasso, or you might end up with a trail of embarrassing typos like a cowboy who missed the target by a mile! Happy coding! 🤠🐴🚀
Ahoy there, coding buccaneers! Sail with me as we navigate the seas of Laravel’s contains method, a swashbuckling tool that helps you find hidden treasure (or strings) in your data.
First off, let’s hoist the anchor and set sail for the land of case sensitivity. By default, this method is as picky as a cat about its fur – it demands exact matches:
use Illuminate\Support\Str;
$isContainingCats = Str::of('This is my name')->contains('my'); // true, but only if 'my' is spelled exactly that way
But fear not, ye scurvy dogs! If you’re seeking a looser cannon, you can pass an array of possible matches to see if your string contains any of the booty:
use Illuminate\Support\Str;
$isContainingTreasure = Str::of('This is my name')->contains(['my', 'booty']); // true if either 'my' or 'booty' is found
Now, let’s say you’ve had too much grog and misspelled your precious treasure. No worries, mate! You can make the method overlook its case by setting the ignoreCase flag to true:
use Illuminate\Support\Str;
$isContainingBooty = Str::of('This is my name')->contains('MY', ignoreCase: true); // true, because it's all about the spirit of piracy, not grammar!
So there you have it, mateys! A fun-filled voyage through Laravel’s contains method. Happy treasure hunting! 🏴☠️💰🚀
Alright, buckle up, Laravel cowpokes! Let’s dive into the wild west of string manipulation with a little rodeo called containsAll. This ain’t your ordinary wrangling job; it’s a sophisticated method that checks if a given string is as slick as a greased snake in a cactus patch, carrying all the values from a dusty ol’ array.
So, you might find yourself needing to know if ‘This is my name’ has all the hidebound charm of [‘my’, ‘name’]. Well, partner, just point your index finger at that string and fire away!
use Illuminate\Support\Str;
$isMyName = Str::of('This is my name')->containsAll(['my', 'name']);
// If you're lucky, you'll get yourself a true blue response!
Now, if you’ve got yourself a posse of rowdy outlaws who don’t care about case sensitivity, fear not! Just set the ignoreCase argument to true like a seasoned sheriff and let it ride:
use Illuminate\Support\Str;
$isMyName = Str::of('This is my name')->containsAll(['MY', 'NAME'], ignoreCase: true);
// Even with those outlaws, you'll still get a clean bill of health!
So there ya have it, partner! You’re now ready to wrangle strings like a seasoned cowhand, rounding up all the values in sight with the containsAll method. Happy coding!
Ahoy there, coding pirates! Ever found yourself in a pickle, trying to decipher some encrypted treasure map? Well, fear no more, for we’ve got the perfect swashbuckling solution - the decrypt method!
This magical spell, hidden deep within the Illuminated Witch’s (that’s Laravel, matey) book of incantations, can transform your encrypted strings from gibberish to glorious, legible text. All you need is a bit of this code:
use Illuminate\Support\Str;
$pirateSpeak = $encryptedMessage->decrypt();
// 'Shiver me timbers! It's plain English!'
Want to transform your text back into secret speak? Fret not, we’ve got you covered with the encrypt method - think of it as a secret decoder ring, but in code form!
Now go forth and conquer those cryptic seas, Captain! 🏴☠️
Alright, let’s dive into the ticklish world of Laravel strings! Meet the deduplicate method - your new best friend in string manipulation. Imagine you’re hosting a dance party, and instead of the dreaded disco-inferno conga line, it eliminates consecutive repeats like a charm!
use Illuminate\Support\Str;
$party = Str::of('The Laravel Framework'); // Our overcrowded dance floor
$party->deduplicate(); // Cue the magic: The Laravel Framework *confetti explosion*
But wait, there’s more! Ever had a string with too many hyphens? Well, your stringy pal deduplicate can handle that, too.
use Illuminate\Support\Str;
$secretCode = Str::of('The---Laravel---Framework'); // A super secret code full of unnecessary hyphens
$secretCode->deduplicate('-'); // *Whisper* The-Laravel-Framework, now isn't that more... elegant?
So go on, give your strings a makeover and dance the night away with Laravel deduplicate! 💃🏻🕺🌈🚀
Ahoy there, code pirates! Let’s set sail through the seas of Laravel with the dirname method – a swashbuckling utility that navigates your file system like a seasoned mariner!
This trusty tool returns the parent directory part of your stringly-articulated treasure map:
use Illuminate\Support\Str;
$map = Str::of('/foo/bar/baz')->dirname();
// Arr, we found ourselves in '/foo/bar'!
Ye be pirating with a purpose, mateys? Then lash up your code with the dirname(2) command to trim unwanted directories from the string:
use Illuminate\Support\Str;
$map = Str::of('/foo/bar/baz')->dirname(2);
// Now we're cruising in style, right ashore at '/foo'!
Don’t ye worry about land ho! Just remember that this method is part of the Str collection – a handy toolkit for string manipulation. Happy sailing, buccaneers!
Ah, the doesntContain() method – a superhero in string-land, saving the day when your strings need to prove they’re not hiding any unwanted secrets!
This friendly little helper determines whether a specific string isn’t sneaking around with a given value. You can think of it as the anti-thesis (not quite opposites, but close enough for our purposes) of the ever-vigilant contains() method.
By default, doesntContain() is a bit of a stickler for correct case – so if you’re looking to catch mismatched cases, this is your guy! But don’t worry, he’s flexible and can adapt to situations where flexibility is necessary:
use Illuminate\Support\Str;
$caseSensitiveSearch = Str::of('This is name')->doesntContain('my'); // true, Mr. Case Sensitive here
But if you’re looking for a more laid-back, easygoing search that ignores case distinctions, just pass the ignoreCase argument as true:
use Illuminate\Support\Str;
$caseInsensitiveSearch = Str::of('This is my name')->doesntContain('MY', ignoreCase: true); // false, he's a real case-ignorer now!
And if you find yourself in need of checking multiple values within a string, just pass an array of those pesky values to the method, and it’ll take care of the rest:
use Illuminate\Support\Str;
$multiValueSearch = Str::of('This is name')->doesntContain(['my', 'framework']); // true, he's a multi-tasker too!
So there you have it – doesntContain(), the string superhero of Laravel, fighting for truth and justice in every search query!
Ahoy there, code enthusiasts! Let’s take a jolly journey into the delightful world of Laravel Strings, shall we? Today, we’re going to learn about a method so enchanting, it makes Cinderella’s glass slipper look like a common sneaker - it’s called doesntEndWith!
This merry little helper function is akin to playing “Heads or Tails” with your strings. It determines whether the given string doesn’t end with the specified value, much like trying to find Waldo in a sea of stripes and spectacles. Here’s a quick example:
use Illuminate\Support\Str;
$result = Str::of('This is my name')->doesntEndWith('dog'); // Yarrr, it returns true!
But wait! There’s more to this pirate party than just one companion. You can also pass an array of values to see if the given string doesn’t end with any of them - kind of like checking for a hidden treasure map among a pile of old parchments:
use Illuminate\Support\Str;
$result = Str::of('This is my name')->doesntEndWith(['this', 'foo']); // Ahoy, it returns true!
$result = Str::of('This is my name')->doesntEndWith(['name', 'foo']); // Eek! It's false, matesy.
So there you have it, folks! With doesntEndWith, you can navigate through your strings with ease and a touch of humor. Happy sailing!
Alright, let’s dive into the zany world of Laravel strings! Today we’re discussing the doesntStartWith method - a superhero for your strings, battling against unwanted prefixes with finesse!
Imagine you have a string like “This is my name”, and you want to check if it doesn’t start with “That”. Fret not, for our Laravel champion is here to save the day:
use Illuminate\Support\Str;
$result = Str::of('This is my name')->doesntStartWith('That');
// If 'This' isn't a secret agent named 'That', it returns true!
But wait, there’s more! You can even present our superhero with an entire squad of unwanted prefixes:
use Illuminate\Support\Str;
$result = Str::of('This is my name')->doesntStartWith(['What', 'That', 'There']);
// If none of those characters are secret agents, it returns true! (Whew!)
Remember, with great power comes great responsibility. So let your strings breathe easy knowing that the doesntStartWith method is on duty, ensuring no unwanted prefixes cause any commotion! 🎉💪🔮
Ahoy there, code wranglers! Let’s dive into the world of cryptic shenanigans with our trusty sidekick, encrypt method!
This cunning chap will take your juicy secrets and turn them into a tangled web of gibberish that even Captain Kirk would have trouble deciphering. It’s like converting plain English to Klingon, but way more secure (and less prone to causing interstellar incidents).
Here’s how you summon this magical beast:
use Illuminate\Support\Str;
$encrypted = Str::of('secret')->encrypt();
Just remember, once you’ve encrypted your sensitive data, you won’t be able to read it without the proper decryption tools. So, don’t go around encrypting your grocery list and expecting to remember what was on it for dinner tonight!
For those brave souls who want to reverse the encryption process (aka when your significant other asks you to repeat that password you swore you’d never forget), check out the decrypt method. It’s like a trusty DeLorean taking you back in time, but without the risk of Marty McFly messing up history.
Now, go forth and secure your data like a cyber ninja! But remember, with great encryption power comes great responsibility (and don’t forget to save that password this time).
Ahoy there, code sailors! Dive into the delightful depths of Laravel’s Str collection method - the endsWith! This enchanting function is akin to a treasure-hunting pirate who sails the seas, seeking to find if your string ends with a particular booty (or value, as we more mundanely call it).
First, let’s set sail on a solitary journey:
use Illuminate\Support\Str;
$pirateResult = Str::of('This is my name')->endsWith('name'); // True! Treasure found, me hearties!
But that pirate’s lonely life isn’t for everyone. Why not let him have a crew? Pass an array of possible endings to the endsWith function:
use Illuminate\Support\Str;
$pirateResult = Str::of('This is my name')->endsWith(['name', 'foo']); // True! Double treasure!
$pirateResult = Str::of('This is my name')->endsWith(['this', 'foo']); // False! No treasure for that trip, matey.
Remember, the endsWith method is a fluent method, meaning it returns the Str instance itself so you can chain multiple calls together like a well-oiled pirate ship:
use Illuminate\Support\Str;
$pirateResult = (Str::of('This is my name')
->endsWith(['name', 'foo'])
->replace('is', 'yarr')) // Aye, replacing 'is' with 'yarr'!
->capitalize(); // Hoist the main sail and raise the Jolly Roger, matey!
Now that’s what I call a swashbuckling Laravel adventure! Keep sailing and treasure hunting with Laravel’s endsWith method. Arrrr!
Ah, the exactly method! It’s like a picky matchmaker in the world of strings. If you’re trying to find out if two strings are a perfect fit for each other, this is your go-to guy (or method, rather).
Here’s an example:
use Illuminate\Support\Str;
$matchStatus = Str::of('Laravel')->exactly('Laravel');
// If they match like a glove on Cinderella's foot, this returns true.
Just remember, it’s all about the perfect fit. This method doesn’t care about close encounters of the second kind or typo-romances. It wants an exact replica, nothing less and nothing more! So, if you’re looking for a faithful companion in your string comparisons, exactly is the one you should be dancing with! 😉💃🎉
Alright, code cowboy! Let’s dive into the excerpt method, the lasso that wrangles your unwieldy strings like a rodeo clown wrangling a bull!
use Illuminate\Support\Str; // Import Str class, it's our trusty steed in this string wild west.
$excerpt = Str::of('This is my name')->excerpt('my', [ // Call excerpt method on 'This is my name' and look for 'my'.
'radius' => 3 // Set the radius to 3, defining how many characters should ride shotgun on each side of the truncated string.
]);
// '...is my na...' - And there you have it, a perfectly tamed excerpt!
Now, the radius option is as important as your trusty six-shooter in this cowboy world. It defaults to 100 characters, but you can adjust it to suit your needs.
But wait, there’s more! You can even change the ominous strings that appear before and after your truncated string with the omission option:
use Illuminate\Support\Str; // Import Str class, still our trusty steed.
$excerpt = Str::of('This is my name')->excerpt('name', [ // Call excerpt method on 'This is my name' and look for 'name'.
'radius' => 3,
'omission' => '(...) ' // Set the omission to '(...) ', replacing the default ellipses.
]);
// '(...) my name' - And now your excerpt comes with a fancy, customized wraparound!
Ride on, partner! Keep those strings under control with the excerpt method, and may your code always be as smooth as a well-oiled six-shooter!
Alright, let’s get this party started! The explode method, our dance floor divider, is the magic trick that splits a string into a jubilant collection using a designated delimiter as its dance cue.
use Illuminate\Support\Str;
$collection = Str::of('foo bar baz')->explode(' ');
// Behold! The confetti cannon fires and we're left with: collect(['foo', 'bar', 'baz'])
Imagine a rowdy bar where our string is the chatter, and the delimiter, well, it’s the bartender shouting “order up!” Every time he yells, our method splits the chat into separate conversations and neatly packages them as a collection. So, next time you find yourself drowning in a sea of words, just call for explode to turn the chaos into a well-organized bar tab! 🍻
Ah, the finish method! Your new best friend when you’re on a quest to add that elusive, missing slash at the end of your stringy adventures. This magical function, much like a trustworthy sidekick, comes in clutch when your strings are as chaotic as a cat playing with a bag of flour. 🐈💔
Here’s where the fun begins:
use Illuminate\Support\Str; // Calling Str is like summoning the string whisperer to your aid!
$string_pirate = Str::of('this/string'); // The pirate doesn't have an ending slash, let's fix that!
// This is where our string whisperer works his magic 🎩✨
$ended_properly = $string_pirate->finish('/'); // Now, our pirate says 'arrrr/string' instead of just 'arrraah'.
But wait, there's more! The string pirate was already ended with a slash? Well then, we better not add another one!
$already_ended = Str::of('this/string/'); // Our string pirate already has an ending slash.
// And so it is, our trusty sidekick doesn't add anything unnecessary 🤐💁♀️
$still_ended_properly = $already_ended->finish('/'); // 'this/string/' remains intact.
Now go forth and conquer the world of strings, one slash at a time! 🏆🎉🌐
Ahoy there, code pirates! If you’ve ever found yourself shipwrecked with a Base64 encoded message, fear not! Laravel’s fromBase64 method is like the SOS signal of the coding world.
Just point it at your encrypted treasure map (that’s your Base64 string) and watch as it decodes it faster than Jack Sparrow can down a mug of grog:
use Illuminate\Support\Str; // Think of this as your compass in the coding ocean
$decoded = Str::of('TGFyYXZlbA==')->fromBase64(); // Remember, 'TGFyYXZlbA==' is just one of Captain Base64's secret codes!
// Laravel, your trusty sidekick in the coding adventure
Sail on, mateys! With fromBase64, even the treacherous seas of encrypted data can’t hold you back.
Ahoy there, code pirates! Sail the sea of strings with us as we dive into the thrilling world of hashing! Arrrr! 🦶️🌴️
The hash method, our trusty compass in Laravel’s port, navigates your humble string through a cryptographic labyrinth, turning it into an indecipherable treasure map that we like to call… a hash! 🏴☠️
To set sail on this adventure, all you need is a string (let’s say ‘secret’) and a compass (the algorithm). Here’s a list of available algorithms for your perusal: [link to algorithm documentation]
use Illuminate\Support\Str;
$hashed = Str::of('secret')->hash(algorithm: 'sha256');
// '2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b'
Now that’s what I call a well-hashed secret! If you ever need to find it again, just follow these coordinates. 🌴️🐢
🎉 Party Time! 🥳
Greetings, coding cowboys and cyberspace cowgirls! Let’s boogie down the syntax highway with the fabulous headline method! 💃🕺
This groovy dance partner is here to transform your string styles from being a wallflower into a radiant centerpiece on the dance floor! It’ll take those strings that are all jumbled up in case, hyphens, and underscores, and smooth them out into a sleek, space-delimited masterpiece with each word’s first letter rocking its best capitals! 🎩
*Invite your new friend Str to the party!*
use Illuminate\Support\Str;
*Let's get this show on the road!*
$headline = Str::of('taylor_otwell')->headline();
*Ta-da! Introducing...*
// Taylor Otwell
*Feeling formal? No worries, Str's got your back!*
$headline = Str::of('EmailNotificationSent')->headline();
*Cue the spotlight...*
// Email Notification Sent
Now that your strings are dancing to the beat of the headline method, it’s time to get down and boogie with all the other Laravel wonders! 💃🕺🎉
Alright, let’s get this party started! The initials method is like a superhero for names. It swoops in, saves the day by transforming your long, boring string into its cool and compact initials. Here’s how you can summon it:
use Illuminate\Support\Str; // Remember, this is Stranger Things we're dealing with!
$initials = Str::of('Taylor Otwell')->transformIntoAbbreviatedSuperheroName()->toUpperCase();
// TO becomes TO, but cooler!
Now, you too can join the ranks of the super-efficient naming elite! 🦸♂️🌍🚀
Ahoy there, coding pirates! Get ready to embark on a whimsical journey through the enchanted seas of Laravel! Today’s destination: the mystical inlineMarkdown method!
Now, this isn’t your average fairy tale princess, nope! It’s more like that magical unicorn that can transform GitHub-flavored Markdown into sparkling inline HTML with the help of CommonMark, the legendary parsing engine (you can learn more about it here: CommonMark).
But hold on to your eyepatches, for inlineMarkdown isn’t just a flashy show-off like its cousin, the markdown method! It’s more refined and sophisticated — it won’t wrap all generated HTML in a blockbuster-level element. Instead, it maintains an elegant and tidy inline format.
So, if you’re looking to make your code as dashingly handsome as Captain Hook’s parrot, give inlineMarkdown a try! Here’s a quick example:
use Illuminate\Support\Str;
$html = Str::of('**Laravel**')->inlineMarkdown();
// <strong>Laravel</strong>
And that, me hearties, is the delightful tale of inlineMarkdown! Now, set sail for your next Laravel adventure!
Ahoy there, Laravel sailors! Let’s talk ‘bout a swashbuckler’s favorite pastime - battling Markdown pirates! 🏴☠️🐘
By the seas of default settings, Markdown is like a ship with wide-open hatches inviting Cross-Site Scripting (XSS) sea monsters. But fear not! Our trusty CommonMark Security docs have got our backs. 📜
To keep those pesky XSS critters at bay, you can use the html_input option to either sanitize or sweep raw HTML clean as a whistle. And the allow_unsafe_links will let you decide whether it’s okay to trust certain links without a second thought.
If you feel like you need to let some raw HTML on board, then it’s time to put the HTML Purifier in the captain’s chair:
use Illuminate\Support\Str;
// Inject: <script>alert("Hello XSS!");</script>
Str::of('Inject: <script>alert("Hello XSS!");</script>')
->markdown([
'html_input' => 'strip',
'allow_unsafe_links' => false,
]);
// Inject: alert("Hello XSS!");
And voila! You’ve successfully tamed the Markdown beast and protected your ship from those XSS buccaneers. Happy sailing, mates! 🌴🐘🚀
Ahoy there, code pirates! Steer clear of the scurvy of incorrect string matching with Laravel’s is method! This seaworthy tool is your compass when navigating the treacherous waters of pattern recognition. Asterisks serve as our trusty wildcard values, helping us sail through even the stormiest of string scenarios!
Shiver me timbers! Let's give it a whirl:
use Illuminate\Support\Str;
Arrr, ye landlubbers! Set course for `foobar`, using the `is` method to test for a pattern like 'foo*'. Hoist the sails, ye scallywags!
$matches = Str::of('foobar')->is('foo*');
Ahoy, matey! We've hit the jackpot – that's a match!
But beware, you landlubbers! If we try to test for 'baz*', we might end up on the wrong island:
$matches = Str::of('foobar')->is('baz*');
Arrr, that's not a match, matey! We'll have to keep searching for buried treasure elsewhere.
So, set sail with Laravel's `is` method and conquer the vast sea of string matching! Yarr, mateys! 🌴🐙🚀
Ahoy there, coders! Sail with me as we navigate the choppy waters of Laravel's `isAscii` method. Picture this: You're in a bustling market, surrounded by merchants hawking their wares – some are ASCII, others... not so much. Your task is to discern which ones are the pure ASCII gold. That's where our trusty helper comes in!
```php
use Illuminate\Support\Str;
$asciiGold = Str::of('Taylor'); // This chap's as ASCII as they come, matey!
$result = $asciiGold->isAscii();
// True! Splendidly ASCII, it is!
But alas, not all merchants are so straightforward. There's a sneaky one who goes by the name of 'ü'. Now, this fellow may seem innocent enough, but don't be fooled – he's a charset chameleon!
$untrustworthyMerchant = Str::of('ü');
$result = $untrustworthyMerchant->isAscii();
// False! This one's got a devious diacritic or two up his sleeve, no doubt!
So there you have it – isAscii method to the rescue! It helps you separate the ASCII from the… well, not-ASCII. Now that we’ve sorted out our merchants, let’s head back to the tavern for a well-deserved drink and some tales of code triumphs!
Ahoy there, Laravel sailors! Ever found yourself in a pickle trying to figure out if your string is as vacant as a deserted island? Fear not, for the isEmpty method has come to save the day! This swashbuckling technique will tell you whether your string is as barren as a cactus in a sandstorm.
use Illuminate\Support\Str;
$isStringEmpty = Str::of(' ')->trim()->isEmpty(); // true, it's like having a party with only the wallflower
$isLaravelStringEmpty = Str::of('Laravel')->trim()->isEmpty(); // false, it's as lively as a pirate convention!
Now you can spend less time pondering and more time coding, you scurvy dogs!
Ahoy there, coders! Let’s dive into the captivating world of Laravel string manipulation, shall we? Today, we’re going to introduce you to a method so chock-full of charm, it could give Cinderella’s carriage a run for its money – the isNotEmpty method!
This enchanting little spell checks if your given string is as lively and spirited as a cat on a hot tin roof… or at least not as silent as a library in a snowstorm. Here’s how to cast it:
use Illuminate\Support\Str;
$result = Str::of(' ')->trim()->isNotEmpty(); // Oooh, so close! But this one's a miss.
$result = Str::of('Laravel')->trim()->isNotEmpty(); // Ta-da! Now that's what I call a hit!
So there you have it – a witty way to ensure your strings are never as dull as dishwater. Keep on coding, dear friends, and may all your variables be happy ones! 🎉🥳
Ahoy there, coding sea dogs! Prepare to hoist the sails of knowledge as we set off on a thrilling journey into the mystical realm of JSON parsing. Buckle up, because things are about to get… well, JSONal!
First off, let’s set our compass to the isJson method, a pirate’s treasure map for determining if a string is a genuine JSON artifact or just some old sea shanty!
use Illuminate\Support\Str;
$json_or_not_json = Str::of('[1,2,3]')->isJson(); // Arr matey! True be tellin' ye, this be proper JSON!
$json_or_not_json = Str::of('{"first": "John", "last": "Doe"}')->isJson(); // Avast! Another true be told!
$json_or_not_json = Str::of('{first: "John", last: "Doe"}')->isJson(); // Arrgh, scurvy dog! This be not JSON, me hearties!
So there you have it, shipmates! The isJson method is a reliable compass to navigate through the treacherous waters of JSON validation. Keep it close and use it wisely, for it’ll save ye from many a sea monster and help ye find the treasure that is your data intact! Yarr-har-har!
Ahoy there, code pirates! Steer clear of the treacherous seas of invalid ULIDs with the mighty isUlid method! This swashbuckling function will help you determine if a given string is as seaworthy as Captain Hook’s parrot – or as lost as the Black Pearl in the Bermuda Triangle.
Call to action: Hoist the anchor, mateys! Get your compass bearings ready and set sail with this code snippet:
use Illuminate\Support\Str;
Ahoy, Stranger! Let's give 'er a whirl:
$result = Str::of('01gd6r360bp37zj17nxb55yv40')->isUlid();
If the ULID is a bonafide buccaneer, you'll receive a jolly 'true'. But if it's as useful as a map with no X marking the spot, you'll find yourself knee-deep in 'false' waters.
Wanna try yer hand at something more landlocked? Well, grab your lasso and take a swing at this:
$result = Str::of('Taylor')->isUlid();
If it's a ULID, you might as well call yourself Jack Sparrow. But if you've just been outsmarted by an ordinary ol' name, don't worry – we all had to learn the hard way that "Pirate Taylor" doesn't cut it on the open seas! 🏴☠️📜
Ahoy there, shipmates! Welcome to the Laravel seaside, where we’re about to delve into the nautical mysteries of the isUrl method. Yar har, let’s hoist the sails and set course for enlightenment!
So, imagine you’ve stumbled upon a mysterious scroll (or string, if you will) on a deserted island, and you’re not quite sure if it contains the elusive treasure map URL. Fear not, matey! The isUrl method is here to help you distinguish if your scroll is indeed a treasure map or just a bunch of old sea shanties!
Here’s a jolly example:
use Illuminate\Support\Str;
$result = Str::of('http://treasure-island.com')->isUrl(); // Avast, that be true matey!
$result = Str::of('Taylor')->isUrl(); // I'm afraid not, it be no treasure map this time.
Now you might be thinking, “What about other sea-worthy protocols, like ‘ftps’ or ‘gopherspace’?” Well, fear not, for the isUrl method is as versatile as a pirate parrot! But if ye wish to restrict your search to specific protocols, ye can do so by passing them along:
$result = Str::of('http://example.com')->isUrl(['http', 'https']); // Only these be accepted, matey!
Now you’re well-versed in the ways of the isUrl method, so go forth and discover hidden treasure maps across the vast Laravel seas! Just remember, a good pirate always double-checks before setting sail! Arr matey!
Alright, code cowboys and codettes! Let’s dive into the isUuid method - a UUID-deciphering wonder that’ll make your dev days shimmer like the vast cosmic ocean it resembles.
use Illuminate\Support\Str;
$uuid_or_not = Str::of('5ace9ab9-e9cf-4ec6-a19d-5881212a452c')->isUuid();
// If it returns 'true', congratulations! You've just found a UUID, and your computer just performed a space-time jump.
// If it returns 'false', don't worry; the universe doesn't end here. It was probably just a mere mortal string.
$result = Str::of('Taylor')->isUuid();
// Guess what? Taylor Swift, though famous, is not a UUID. Sorry, Taylor!
Now, you might be wondering: “What if I’ve got a UUID with some fancy versions?” Well buckle up, because this method can validate UUIDs by version (1, 3, 4, 5, 6, 7, or 8). Just like how your favorite superhero has an origin story, your UUID can have a version too!
use Illuminate\Support\Str;
$is_version_4 = Str::of('a0a2a2d2-0b87-4a18-83f2-2529882be2de')->isUuid(version: 4);
// If it returns 'true', you've got yourself a version 4 UUID. Your UUID is officially promoted to the rank of Avengers!
$is_version_1 = Str::of('a0a2a2d2-0b87-4a18-83f2-2529882be2de')->isUuid(version: 1);
// If it returns 'false', your UUID doesn't qualify for the Justice League. But don't despair, there's always a new adventure waiting!
That’s all, folks! Now you can effortlessly sail through the seas of UUIDs with the isUuid method on board. It’s like having an invisible lifebuoy for your string-navigating journey!
Ahoy there, coding pirates! Sail the seas of syntax with me as we delve into the enchanting world of Laravel’s kebab method, a swashbuckling tool that’ll make your strings walk the plank and dance the jig of kebab-case.
So grab your peg leg, eyepatch, and a steaming mug of coffee (or rum), because we’re about to embark on an adventure worthy of any buccaneer!
First off, hoist the Jolly Roger and let’s bring Str on board! This handy utility class is your new best mate in the coding seas.
Now, with our trusty sidekick by our side, we can seize the day and kebab any string that dares cross our path:
use Illuminate\Support\Str; // We've got to make friends with Str before we can command it!
$newString = Str::of('fooBar')->kebab(); // 'FooBar' sails into the harbor of 'foo-bar', transformed by our fearless leader, kebab!
And just like that, fooBar has been made to walk the plank, only to emerge as a dashing ‘foo-bar’. Arrrr matey, Laravel’s kebab method is the key to turning your unwieldy strings into a parrot-worthy dance!
Ahoy there, code pirate! Ever found yourself in a bind trying to tame that wild uppercase string of yours? Fret not, for the lcfirst method is here to lend a hand!
This swashbuckling technique will return your given string with the very first character demoted to lowercase, making it easier on the eyes. Yarr, just use it like so:
use Illuminate\Support\Str;
$string = Str::of('Foo Bar')->lcfirst();
// Behold! 'foo Bar' now looks far more palatable!
Now go forth and conquer the seven seas of proper case formatting, you brave soul! Happy coding! 🏴☠️🔰
Ahoy there, code wranglers! Fancy a dash of humor with your Laravel knowledge? Well, buckle up, because we’re about to embark on a joyride through the world of string length estimation!
First off, let me introduce you to our trusty sidekick: The length method. This cheeky chap is akin to a pirate’s parrot, always ready with the count of whatever string you’ve got tied up in your rigging. Here’s how you call upon it:
use Illuminate\Support\Str;
$parrotSays = Str::of('Laravel')->length();
// 7... buccaneers, prepare to be surprised!
Now, don’t be alarmed if you hear a squawk of “7” from your monitor after running this code. That’s just our friendly parrot, Str::of('Laravel'), letting you know the number of letters in his new favorite phrase!
But wait! There’s more! By chaining the limit method with length, you can clip the wings off your string and make it fly only as far as you want:
use Illuminate\Support\Str;
$shortenedParrot = Str::of('Laravel')->limit(3);
// "Lar"... aye, not quite the full phrase, but we're getting there!
So there you have it, me hearties! The length method is as essential to your Laravel toolkit as a compass is to any ship voyaging the seas. Now go out and make beautiful music with strings… or something like that. Yarr!
Oh, the limit method! It’s like your digital pair of scissors, but for strings (or in this case, maybe more like a chain saw). Cutting down the verbosity without losing any essential parts – that’s what we’re talking about here! 🪓
Here’s a little demonstration:
use Illuminate\Support\Str;
$chopped = Str::of('The quick brown fox jumps over the lazy dog')->limit(20);
// The quick brown fox... (Feeling the need to sing a shorter version of that classic poem?)
Want to add some ellipses at the end? Just like that:
$chopped = Str::of('The quick brown fox jumps over the lazy dog')->limit(20, ' (...)');
// The quick brown fox (...)
Don’t like abrupt endings? Preserve those complete words using the preserveWords argument. It ensures that your truncated string ends at a whole word:
$chopped = Str::of('The quick brown fox')->limit(12, preserveWords: true);
// The quick... (Now we're really making it hard for Aesop to tell his tale!)
And there you have it! Happy string trimming! 🌿✂️😊
Ahoy there, code swashbucklers! Sail the seas of string manipulation with Laravel’s lower method! This magical spell turns your uppercase pirate speak into commoner’s tongue faster than you can say “Yarr!” 🏴☠️
use Illuminate\Support\Str;
$parrotSpeech = Str::of('LARAVEL'); // A parrot, proudly squawking its love for Laravel
$properConversation = $parrotSpeech->lower(); // Translates to: "laravel", much easier for landlubbers to understand! 💭
So, if you’re ever in need of taming your code, this method will be your trusty sidekick. Just remember: proper nouns may still require a hearty dose of good manners and capital letters… but don’t worry, we’ve got other methods for that! 😉
Happy coding, mateys!
Ahoy there, code cowboys and codettes! 🤠 👓 Let’s dive into the wild west of Markdown with Laravel’s trusty sidekick, markdown(). This trusty ol’ method is as slick as a greased prairie dog, transforming GitHub-flavored Markdown into shiny HTML.
Use ya six-shooter, Illuminate\Support\Str;
$html = Str::of('# Laravel')->markdown();
// Saddle up and ride off with a fine <h1>Laravel</h1>
$html = Str::of('# Taylor <b>Otwell</b>')->markdown([
'html_input' => 'strip',
]);
// Tame that wild HTML beast, leaving us with a civilized <h1>Taylor Otwell</h1>
Ride on!
Alrighty, let’s dive into the wild world of Markdown Security, shall we? 🎉🤖
First off, it’s important to know that by default, Markdown loves raw HTML… a bit too much. This can lead to Cross-Site Scripting (XSS) nightmares when combined with user input. But fear not! The wise folks at CommonMark have provided a security guide (just follow this link if you fancy a read).
To save the day, we’ve got two options: html_input and allow_unsafe_links. The former lets you either escape or strip raw HTML, while the latter lets you decide whether to allow unsafe links in your Markdown.
Now, if you find yourself needing a little bit of raw HTML, don’t just go around inviting XSS over for dinner! Instead, put your Markdown through an HTML Purifier:
use Illuminate\Support\Str;
// Let's imagine user input is 'Inject: <script>alert("Hello XSS!");</script>'
Str::of('User Input')->markdown([
'html_input' => 'strip', // Escapes raw HTML by default, but can be changed to 'parse' if needed
'allow_unsafe_links' => false, // You decide!
]);
// Result: <p>Inject: alert("Hello XSS!");</p>
And just like that, we’ve saved the day… and maybe even the world! 🌍🦸♂️
Ahoy there, coders! Let’s strut our stuff with Laravel’s mask method – a secret agent in the world of strings! This bad boy can transform your plain Jane data into a cloak-and-dagger affair, perfect for disguising email addresses and phone numbers.
use Illuminate\Support\Str;
$email = Str::of('[email protected]')->mask('*', 3);
// tay***************
But wait! There’s more! With this method, you can even provide negative numbers as your secret coordinates to start masking from a given distance from the end of the string:
$email = Str::of('[email protected]')->mask('*', -15, 3);
// tay***@example.com
Or maybe you're feeling particularly covert and want to mask from both ends? No problemo!
```php
$email = Str::of('taylor@example.com')->mask('*', 4, -4);
// tayl**********.com
Remember, with great power comes great responsibility – but with Laravel’s mask method, you can make your data dance like a secret agent in a spy movie, all while keeping it safe and sound!
Ahoy there, code swashbucklers! Prepare to embark on a thrilling journey through the vast seas of strings and patterns with Laravel’s match method! This enchanted compass will guide you towards the hidden treasures within your text, using the mystical power of regular expressions.
Bring forth the Str class, brave sailor:
$booty = Str::of('Parrot and Compass')->match('/Compas/'); // Empty chest awaits
But fear not! By wielding the correct pattern, you can unearth more than just compasses:
$booty = Str::of('Parrot and Compass')->match('/Parro(.*)/'); // Treasure: 't' and 'd'
And if you’re after a whole shipful of matches, hoist the Jolly Roger and call upon the matchAll method! This fearsome pirate will return an array containing every match found within the string. Arrr matey!
Str::of('Seven seas, five parrots')->matchAll('/Parrot/');
// Treasure map: ['Parrot', 'Parrot', 'Parrot', 'Parrot', 'Parrot']
So set sail and conquer the string seas with Laravel’s match method! Don’t forget to bring plenty of rum, a trusty parrot, and your favorite cutlass. Happy coding, mateys! 🏴☠️🚀🌴
Hey there, code cowboys and code wranglers! 🤠 Let’s gallop through the wild west of strings with Laravel’s trusty steed - the matchAll method! 🐎
This little horse can round up all the parts of a string that fit a snuggly regular expression pattern, like a seasoned cowboy herding cattle in the great plains.
use Illuminate\Support\Str;
$roundup = Str::of('bar foo bar')->matchAll('/bar/');
// And lo and behold, you've got yourself a corral full of 'bars'! collect(['bar', 'bar'])
But that ain’t all! If you lasso a matching group within the expression, Laravel will return a collection of just those wranglers that match.
use Illuminate\Support\Str;
$roundup = Str::of('bar fun bar fly')->matchAll('/f(\w*)/');
// And hooray! You've caught 'un' and 'ly'. collect(['un', 'ly'])
Now, if the prairie doesn’t have any matches, fear not! This method will return an empty corral (collection), just like a real cowboy would. Happy rounding up! 🤠🚀
Ahoy there, code wranglers! Let’s sail into the enchanting realm of Laravel Strings, where magic meets logic in a symphony of characters! Meet the isMatch method, your new best friend when it comes to pattern recognition in strings. It’s like having Sherlock Holmes on your keyboard!
use Illuminate\Support\Str; // Don your cape and pick up your magnifying glass, my dear
$result = Str::of('foo bar')->isMatch('/foo (.*)/'); // The string "foo bar" matches the pattern? Captain Ahab, grab a telescope!
// true, you're onto something!
$result = Str::of('laravel')->isMatch('/foo (.*)/'); // Alas, no match found, move along, nothing to see here.
// false, sorry about that!
Now, go forth and conquer the seas of text analysis with this mighty method by your side!
Ahoy there, code pirates! Steer clear of the tedious task of adding a newline to your strings like a common landlubber. With Laravel’s newLine method, you can sail smoothly into the realm of elegant coding, leaving those clumsy "\n" behind!
Ahoy matey! Let's hoist the sails on some Laravel magic:
use Illuminate\Support\Str;
$shipShape = Str::of('Laravel')->newLine()->append('Framework');
// 'Laravel
// Framework' - Arrgh, ye strings have never looked swifter!
Now, if you want to dress both sides of your string with a newline, you can do so by invoking the padBoth method, just like a true shipwright:
Tie yer strings up tight with some Laravel flair:
use Illuminate\Support\Str;
$symmetrical = Str::of('Laravel')->newLine()->padBoth(4)->append('Framework');
// ' Laravel
// Framework ' - Aye aye, Captain! Perfectly aligned!
So hoist the Jolly Roger high and embrace this new method, my friends. It’s time to leave those boring strings in the dust as you sail towards superior code mastery!
Ahoy there, code pirates! Buckle up and let’s dive into the swashbuckling world of Laravel’s padBoth method, a string-padding powerhouse that’ll leave your array arrays looking shipshape and Bristol fashioned!
This nifty function is an anchor to PHP’s own str_pad function, providing a two-pronged approach to padding strings—yep, you guessed it—on both sides until they reach the desired length. So if your string feels a bit wan and flabby, this method’ll beef it up, adding padding like a master caulker!
use Illuminate\Support\Str;
// Padding 'James' with underscores to make it 10 characters long, resulting in: '__James___'.
$padded = Str::of('James')->padBoth(10, '_');
// If no padding character is provided, it defaults to spaces—so 'James' becomes ' James '.
$padded = Str::of('James')->padBoth(10);
So hoist the Jolly Roger, mateys, and start pad-padding your arrays with padBoth! It’ll keep your code as tight as a sailor’s knot and your strings looking spick-and-span! Yarr! 🦞
Alright, let’s spice up your string game with the padLeft method, a Laravel twist on PHP’s classic str_pad function. Imagine you’re hosting a fancy soiree and some guests show up underdressed - you wouldn’t want them standing out, now would you? So, we pad their left side with something trendy until they blend in seamlessly!
use Illuminate\Support\Str;
// Let's say James decided to rock up unannounced and didn't bring enough star power.
$james = Str::of('James');
// We decide he needs a dash of coolness, so we give him '-='.
$padded_james = $james->padLeft(10, '-=');
// And voila! "-=-=-James" - now that's one stylish guest list.
But what if James finally realizes he needs to make a grand entrance? You can remove the extra padding by simply not specifying the padding string:
$padded_james = $james->padLeft(10);
// Now we have some breathing room with " James" on our guest list.
Remember, just like at a party, every string deserves to be the right length! 🎉🥳🙌
Ahoy there! Buckle up, mateys! In the grand ol’ world of Laravel, we’ve got a swashbuckling method that goes by the name of padRight. It’s akin to a pirate filling his parrot’s cage with doubloons, but instead of feathered critters and gold, we’re dealing with strings and padding!
str_pad is PHP’s trusty sidekick in this tale, and padRight is the Laravel captain who wraps it up for a smoother sail. So, what’s this method do exactly? Well, it pads the right side of a string with another string until our final string reaches its desired length.
Here’s an example to help illustrate:
use Illuminate\Support\Str;
// Let's say we have Captain James and we want him to fit snugly in a 10-letter logbook entry
$padded = Str::of('James')->padRight(10, '-'); // 'James-----'
// But what if we didn't provide the padding string? Well, old matey, the method will use spaces instead!
$padded = Str::of('James')->padRight(10); // 'James '
In plain English, padRight is your new best friend when you need to ensure every entry in your logbook has the same number of stars or dashes—or whatever floats your boat! Just remember, with great power comes great responsibility, so don’t pad and sail away without knowing where you’re headed! ☠️🏴☠️🚀
Ahoy there, shipmates! Sail the seas of code with me as I guide you through the captivating world of Laravel’s pipe method! This swashbuckling technique is like a magical parrot perched on your shoulder, whispering secrets into your ear about transforming strings.
Imagine setting sail with a plain ol’ string named ‘Laravel’. Now, you want to take its hash using MD5 (like a pirate might scribble in his logbook). With the pipe method, you can pass it to a trusty callable for safekeeping:
use Illuminate\Support\Str; // Think of this as hoisting the Jolly Roger
use Illuminate\Support\Stringable; // A bit like donning an eye-patch and peg leg
$hash = Str::of('Laravel') // Our trusty vessel, filled with 'Laravel'
->pipe('md5') // The pirate-approved method for hashin' the goods
->prepend('Checksum: '); // A touch of flair to make it more presentable
// Ahoy! We've reached our destination: 'Checksum: a5c95b86291ea299fcbe64458ed12702'
Now, let’s imagine we’ve caught another string fish named ‘foo’. With the pipe method, you can turn it into a delectable ‘bar’ with the help of a custom callable:
$closure = Str::of('foo') // Our freshly-caught string fish, 'foo'
->pipe(function (Stringable $str) { // A cunning pirate callable ready to work its magic
return 'bar'; // Transforms our fish into a delightful 'bar'
});
// Ta-da! Our transformed treasure: 'bar'
So there you have it, matey! The pipe method is like the trusty compass guiding your Laravel adventures. It helps transform strings while keeping them shipshape and Bristol fashionable! Hoist the colors and set sail for code mastery!
Ahoy there, code wranglers! Dive into the world of automatic grammar transformations with Laravel’s plural method - the magical potion that turns your ‘singular’ words into ‘plural’ ones (and no, we’re not talking about frogs here).
use Illuminate\Support\Str;
$pluralCar = Str::of('car')->plural(); // Just in case you thought your car was the only one on the road... it's not!
$pluralChild = Str::of('child')->plural(); // Multiply your family by one (in a good way)!
Now, how about a little number game? With plural, you can play with numbers and get the singular or plural form of your string like a pro:
use Illuminate\Support\Str;
$pluralChild = Str::of('child')->plural(2); // Here come 2 children, running as fast as they can!
$pluralChild = Str::of('child')->plural(1); // And one child decided to play alone...
But wait! If you’re dealing with big numbers and need to sound fancy, Laravel’s prependCount is just what the doctor ordered:
use Illuminate\Support\Str;
$label = Str::of('car')->plural(1000, prependCount: true); // 1,000 cars! You're not driving a common car, are you?
So there you have it, folks! With Laravel’s plural method, your code will be as fluent as a well-oiled assembly line and as stylish as the latest fashion trends. Happy coding! 🤘
Ahoy there, code pirates! Let’s set sail through the choppy waters of Laravel string manipulation with the position method, a trusty compass that helps us find our treasure (er, substrings) within a sea of text (er, strings).
But beware! If ye substring isn’t in the string, this method will return the cryptic and ominous ‘false’, leaving you wondering if your map is cursed or not.
Use yon Str class like ye would swab a deck:
$position = Str::of('Hello, World!')->position('Hello'); // Arrgh, found it at position 0!
And if ye be lookin' fer 'W', it can be spotted at position 7:
$position = Str::of('Hello, World!')->position('W'); // Set a course for the 7th starboard watch!
Remember, ye must arm thyself with the Str class before setting sail on this method. And as always, happy coding, you brave navigators of code!
Ahoy there, code pirates! Let’s set sail on a linguistic adventure with the delightful prepend method! This nautical navigator isn’t just a cleverly named sea shanty; it’s a Laravel gem that lets you attach your chosen booty (values) at the very beginning of your humble string.
use Illuminate\Support\Str; // Grab your compass and charts!
$string = Str::of('Framework')->prepend('Laravel '); // Yo ho ho, Laravel Framework is on board now!
// Laravel Framework
Don’t forget to keep an eye out for more exciting methods in our Laravel documentation treasure trove. Happy coding, mates! 🌴🚀
Ah, the grand remove method, a veritable magician of the string realm! It’s like having your very own Erasmus Spellman at your service (if he were into Laravel and strings instead of puzzles).
This enchanting sorcerer casts its spell on your strings, vanishing the given value or coven of values with an elegance that would put even Casper the Friendly Ghost to shame.
use Illuminate\Support\Str;
$string = Str::of('Arkansas is quite beautiful!')->remove('quite ');
// After a swift incantation, voila! Arkansas is beautiful!
You can even cast a wildcard spell by passing false as the second param to ignore case while removing strings.
<a name="method-fluent-str-repeat"></a>
So, next time you’re battling pesky string repetitions and unwanted phrases, don’t hesitate to summon the remove method! It’s like having a personal genie dedicated to your string woes. Now, isn’t that magical?
Ahoy there, code pirate! Steer clear of scurvy by learning the swashbuckling secrets of Laravel’s repeat method. This treasure chest of a function lets you fill your sails with as much repetition as you need, without ever having to mutter “shiver me timbers” at your keyboard in frustration!
use Illuminate\Support\Str; // Import the magical pirate's compass that helps us navigate these waters
$parrotCries = Str::of('aarrr'); // Initialize our parrot's cries, it's never too early for some nautical talk!
$repeatedParrot = $parrotCries->repeat(5); // Sail the seven seas with five times the cries of 'aarrr', matey!
// aaarrrraaaarrraaaarrrr
Now, that’s what I call a shipshape repetition, isn’t it? Just remember to keep your repeat in check, or you might end up with a parrot squawk-storm that’ll have even the most stoic captain raising an eyebrow! But hey, who doesn’t love a good ‘aarrr’ now and then?
Ahoy there, coding pirates! Buckle up as we delve into the swashbuckling world of Laravel’s replace method! Aye, this versatile swabbie swaps out a specific string within another, like a barkeep replacing rum with water for the sobriety-challenged crewmember.
use Illuminate\Support\Str;
$swapped = Str::of('Laravel 6.x')->replace('6.x', '7.x');
// Transforms into: Laravel 7.x, but without the scurvy
The replace method is as picky as a prima donna at a masquerade ball – by default, it only changes the string if the capitalization matches. But fear not, ye landlubbers, for there’s a way to make it less fussy!
$swapped = Str::of('macOS 13.x')->replace(
['macOS', 'OS'], // Replace macOS and OS with iOS
['iOS', 'ix'], // Swap 'i' with 'i' and 'O' with 'x', because why not?
caseSensitive: false // Make it less pretentious
);
Now you can sail the seas of code without worrying about a pesky string here or there. Happy coding, matey!
Ahoy there, code wranglers! Steer clear of the tedious str_replace boat and sail into the harbor of efficiency with Laravel’s replaceArray method! This swashbuckling technique can replace a specific value in a string, pirate-style, using an array!
Grab your ropes, mateys! Here's how you use it:
Use the magical Str class and summon `replaceArray`:
use Illuminate\Support\Str;
$string = “Arrrgh, the event will take place ‘round ? and ?”;
$replaced = Str::of($string)->replaceArray(’?’, [‘Shiver me timbers 8:30’, ‘Grogg 9:00’]);
// Now yer pirate parley reads: “Arrrgh, the event will take place round Shiver me timbers 8:30 and Grogg 9:00”
Huzzah! With `replaceArray`, ye can save precious time and energy, leaving more of both for pillaging treasure or sipping grog. Hoist the Jolly Roger and set sail for success!
Ahoy there, code adventurers! Let's talk about a swashbuckling method in Laravel that'll make you feel like Captain Swapbeard! It's the `replaceFirst` method, a one-eyed pirate looking for a specific value to replace on your strings!
Here's how it works:
```php
use Illuminate\Support\Str;
$replaced = Str::of('the quick brown fox jumps over the lazy dog')->replaceFirst('the', 'a');
// a quick brown fox jumps over the lazy dog
In this example, our trusty method was told to search for ‘the’ and replace it with ‘a’. And just like that, we transformed ‘the quick brown fox’ into ‘a quick brown fox’! This method is perfect for situations when you want to rename old friends without changing their entire identity. Or, you know, replacing a word in your code. But let’s not get too serious, shall we? Happy coding, buccaneers!
Ahoy there, code wranglers! Sail with me into the lively world of Laravel strings, where the high seas of data manipulation await! Today’s stop: replaceLast, a swashbuckling method that’ll make your code as nimble as a cat on a hot tin roof!
Ever find yourself in a pickle with an unwanted word at the tail end of your string? Well, fear not! The replaceLast method is here to save the day (and your code)!
use Illuminate\Support\Str;
$replaced = Str::of('the quick brown fox jumps over the lazy dog')->replaceLast('the', 'a');
// the quick brown fox jumps over a lazy dog - pirate style!
With replaceLast, you can swap out that final word like Captain Jack Sparrow trading his compass for rum. So, hoist the Jolly Roger of code refactoring and set sail for cleaner, tidier strings with Laravel’s mighty replaceLast method! Yarr matey!
Ahoy there, Laravel Pirates! Ready to set sail on the high seas of string replacement? Buckle up, because we’re about to dive into the replaceMatches method!
Picture this: you’ve just found a treasure map with numbers, symbols, and all sorts of gibberish. But fear not, for your trusty compass - the replaceMatches method - is here to help! This handy dandy tool navigates through your string, replacing any portions that match a pattern with a swashbuckling replacement string.
use Illuminate\Support\Str;
$cleanedMap = Str::of('(+1) 501-555-1000')->replaceMatches('/[^A-Za-z0-9]++/', '');
// '15015551000' - Arrr, no more silly symbols!
But wait, there’s more! The replaceMatches method also lets you use a clever closure to perform your own custom replacement logic. Imagine stumbling upon a riddle in your treasure map: “Find the number that comes before 3.” No worries matey, just throw in a closure and let it handle the detective work for ya!
use Illuminate\Support\Str;
$rearrangedMap = Str::of('123')->replaceMatches('/\d/', function (array $matches) {
if ($matches[0] == '2') {
return '0'; // Ah, there it is! The number before 3.
} else {
return $matches[0];
}
});
// '[1][0][3]' - Arrr, we found the number that comes before 3!
So hoist the main sail and let the replaceMatches method steer your string replacement adventures with ease! Yarrr, you’ll be conquering treasure maps like a pro in no time!
Alright, strummers! Let’s dive into the captivating world of Laravel strings, where magic happens and syntax sings. Today, we’re going to serenade you with the enchanting replaceStart method, a string charmer that knows just how to dance with your data!
use Illuminate\Support\Str;
$greeting = Str::of('Hello World'); // Our string debutante
Now, if we want to make our dashing 'Hello' swoon for 'Laravel', all it takes is a little `replaceStart` magic:
$transformed = $greeting->replaceStart('Hello', 'Laravel'); // Laravel World, swoon!
But what if 'World' doesn't quite catch our 'Laravel' hero's eye? Well, no need to fret. Just give it another spin:
$untransformed = $greeting->replaceStart('World', 'Laravel'); // Hey, old habits die hard! It still loves the original World. Ain't love grand?
Remember, dear strummers, replaceStart only charms the first appearance of the given value. If you’re looking to sweep a few more strings off their feet, be sure to check out other string methods in Laravel’s arsenal! Keep those strings dancing! 💃🏼🕺🏼🎶
Ahoy there, coder! Sail with me through the sea of strings and let’s discuss the delightful replaceEnd method, a pirate’s treasure trove of a tool in Laravel. This swashbuckling technique does one thing, and one thing only: it replaces the last appearance of the value you specify, but only if that value is anchored at the end of the string (like Captain Jack Sparrow at the Black Pearl).
use Illuminate\Support\Str;
$newPirateSlogan = Str::of('Yo ho, Yo ho, a bottle o' rum')
->replaceEnd('rum', 'Laravel'); // 'Yo ho, Yo ho, a bottle o' Laravel'
$rebelingAgainstOldPhrases = Str::of('Hello World')
->replaceEnd('Hello', 'Laravel'); // 'Hello World' (no changes because 'Hello' isn't at the end)
Remember, just like a good rum recipe, precision is key: the replaceEnd method only works its magic when the specified value is nestled comfortably at the string’s end. Happy coding, buccaneers! 🏴☠️🌴
Ahoy there, coding pirates! Dive into the depths of Laravel’s magical treasure chest with the scan method! It’s like a parrot deciphering hidden treasure maps, but instead of gold and jewels, we’re turning your strings into shiny new Collections!
This enchanting technique uses a format that’s supported by the legendary PHP function called sscanf. Imagine it as the Kraken of pattern matching! It’s quite the catch for those seeking to tame their strings. 🦑
Let’s set sail on a code example:
use Illuminate\Support\Str;
$collection = Str::of('filename.jpg')->scan('%[^.].%s');
// Ahoy! Ye end up with collect(['filename', 'jpg'])!
Now, what does that arcane pattern mean? Well, it’s telling our humble pirate helper to look for any non-dot characters (like ‘filename’) followed by a dot and some other characters (like ‘.jpg’). You could adjust the pattern to fit your treasure hunt needs! Happy sailing, matey! 🏴☠️
Ahoy there, coders! Let’s embark on a delightful journey through the enchanting world of Laravel, shall we? First stop: The singular method - your one-way ticket to transformationville!
This magical method, much like a skilled tailor, takes a string and sews it into its more refined, sophisticated sibling. It’s like Cinderella’s fairy godmother, but for data types instead of prom dresses.
The singular function supports a variety of languages (Laravel’s Pluralizer has quite the linguistic repertoire, you know). Just think of it as a polyglot party host, greeting each language with equal enthusiasm and grace:
use Illuminate\Support\Str;
$singularCar = Str::of('cars')->singular();
// car... voilà! One less 's' to worry about!
$singularChild = Str::of('children')->singular();
// child, because you can never have too many of those adorable little mites, right?
So there you have it, folks! The singular method - your new BFF in data transformation. Now, who’s ready to dance the night away with some delightful coding? 🎉🕺🏼
Oh, the slug method is like a superhero for your words! It takes a string, and with its magical powers, it transforms it into a URL-friendly creature that even the pickiest SEOs will approve.
Here’s how you can summon this superhero in your Laravel project:
use Illuminate\Support\Str;
$slug = Str::of('Laravel Framework')->transformIntoUrlBeast('-');
// And voila! Your beast is named 'laravel-framework'
Just imagine the excitement of watching your words evolve into a form that’s not only understandable by humans but also by search engines. It’s like giving your words a makeover for a glamorous red carpet event! 🤩🌟
Ahoy there, coders! Ever found yourself in a pickle trying to convert your string into the elusive snake_case? Fear not, for we’ve got just the Laravelish solution you’ve been craving!
Welcome to the snake method – the unsung hero of our string-wrangling arsenal. This bad boy transforms your wild and wooly fooBar into a tamed, civilized foo_bar. Just remember to give it a call with the Str class on speed dial:
use Illuminate\Support\Str;
$politeFellow = Str::of('fooBar')->snake();
// Voila! You've got yourself a well-behaved 'foo_bar'.
So, next time you need to tame your string beasts, remember the snake method. It’s like a stylish haircut for your text, making it fit right in with the rest of your code. Happy coding! 🎉🎈🐍
Ahoy there, coders! Buckle up for a whirlwind tour of Laravel’s split method - it’s the party trick your strings have been waiting for!
You see, this delightful little number splits a string into a glorious collection using a powerful sorcery known as regular expressions. So grab your crystal ball and let’s take a peek:
use Illuminate\Support\Str;
$potions = Str::of('elixir of life, unicorn tears, dragon's breath')->split('/[\s,]+/');
// voilà! collect(["elixir of life", "unicorn tears", "dragon's breath"])
In this enchanting example, we transformed our chaotic concoction into a well-behaved collection. Now that’s magic!
Remember to sprinkle some caution when using regular expressions, as they can be as mischievous as the three-eyed goblins of Mordor. But don’t worry, this method will leave you with a clean and orderly collection every time. Happy brewing! 🍻
Alright, coding cowboy (or cowgirl!), meet your new best friend in the wild west of strings: squish. Picture this, you’ve just roped in a long-winded string and it’s got more white space than a Wyoming ranch. But fear not, for squish will wrangle that unwieldy beast into a sleek and streamlined cowpoke!
Gather round, campers! Let's call upon our trusty helper, Illuminate\Support\Str:
$string = Str::of(' laravel framework '); // Your wild and untamed string
Now, let the `squish` method do its magic:
$string->squish(); // Transforms into: laravel framework
And there you have it! A clean, well-behaved string for your Laravel herd. Just like corralling cattle in the old west, sometimes you need a little help to get things tidied up. Happy coding! 🤠🐄🌮
Ahoy there, code pirates! Steer your ships to Laravel’s enchanted string method land, where the code is as smooth as a shipwrecked sailor’s dance and the logic flows like grog from a bounty barrel. Let me tell you about the start method, mateys!
This here method adds a single instance of your specified value to a string, only if it doesn’t already start with that value. It’s like giving Captain Hook an extra hand without making him a double-headed monster. Confused? Let me set sail and clarify:
use Illuminate\Support\Str; // Import Str class
// Setting sail on a string "this/string" without the starting '/'. Let's add it!
$adjusted = Str::of('this/string')->start('/');
// /this/string - Ah, it now has the captain's mark! But wait, what if we already have it?
// Aye-aye, Captain, this time "this/string" already starts with '/'. The method won't change a thing.
$adjusted = Str::of('/this/string')->start('/');
// /this/string - Still the same ol' string! But don't worry, no ships were harmed in this operation.
Now that your ships are armed with this knowledge, you can confidently navigate Laravel’s sea of strings without fearing unexpected changes in your course! Keep the code piracy going, and remember to keep it fun, but always stay shipshape!
Ahoy there, coding sailors! Prepare to hoist the sails of semantics with Laravel’s startsWith method! This be a mighty fine way to check if a string starts its journey with a specific word or phrase.
Imagine you’re at a grand ball and trying to find Mr. Darcy in a sea of men (or women, no judgment here). Instead of asking each person “Is your name Fitzwilliam?” one by one, use the startsWith method to quickly narrow down your search:
use Illuminate\Support\Str;
$result = Str::of('Fitzwilliam Collins')->startsWith('Fitzwilliam');
// true, you've found him! Now go get 'em, Jane!
But what if Mr. Darcy is in disguise and using a different name? Well, matey, simply use an array to check multiple possibilities:
use Illuminate\Support\Str;
$result = Str::of('William Collins')->startsWith(['Fitzwilliam', 'William']);
// true, you've found him in disguise!
Remember, even at a ball, the best dancers are those who can code efficiently. So, dance your way through your applications with Laravel’s startsWith method!
Ahoy there, coders! Let’s dive into the delightful world of stripTags, the Laravel method that can make your HTML string as bare as a newborn baby’s crib! 👶️
Imagine you’ve caught a string full of pesky HTML and PHP tags - it’s like finding a sandcastle on your beach towel. But fear not, stripTags is here to sweep them away with just one line of code:
use Illuminate\Support\Str;
$result = Str::of('<a href="https://laravel.com">Taylor <b>Otwell</b></a>')->stripTags();
// Out goes the fancy formatting, leaving us with "Taylor Otwell" - a clean slate for further adventures! 🌴
But wait, what if you’re a stickler for detail and can’t bear to part with some tags? Well, stripTags is as flexible as a Cirque du Soleil performer. You can even tell it to leave specific tags in place:
$result = Str::of('<a href="https://laravel.com">Taylor <b>Otwell</b></a>')->stripTags('<b>');
// "Taylor <b>Otwell</b>" remains, with just the bold tags still shining bright! 🌈
So, next time your string is full of tags and you’re yearning for a cleaner, simpler life, remember: stripTags has got your back! Keep coding, keep laughing, and above all, keep tagging (but not in the HTML sense)! 🎉🎈🚀
Alright, grab your monocles and deerstalkers, Laravel detectives! Time to dive into the fascinating world of string manipulation with our trusty sidekick: studly. No, not the dog from Flintstones, but a method that turns strings into proper gentlemen in the realm of camelCase.
use Illuminate\Support\Str; // Calling it Str is like naming your car 'Vroom'. It's just funny!
$gentleman = Str::of('foo_bar')->studly();
// Out pops our new acquaintance, FooBar. Quite the catch, wouldn't you say?
But wait, there’s more! This method is not only charming but also fluent, meaning it lets you chain commands like a well-oiled programming machine. And with that, we bid adieu to our friendly string ‘foo_bar’, and welcome its refined alter ego, FooBar!
Alright, buckle up, code cowboys! Today we’re diving into the wild, wild west of Laravel strings with the substr method. This ain’t no ordinary sheriff in town, it’s a string-chopping, lasso-swinging cowboy that’ll wrangle your strings like nobody’s business!
use Illuminate\Support\Str;
$string = Str::of('Laravel Framework'); // Our trusty steed, a string as long as the Oregon Trail.
$string->substr(8); // 8 clicks west and we've reached "Framework". Cowboy coding at its finest!
But wait, there's more! If you fancy a smaller chunk o' strings, you can specify the length too:
$string->substr(8, 5); // Now we're hitchin' up only "Frame"!
You see, this substr method ain’t just a regular ol’ string method; it’s a rodeo ride where you’re the rider, cutting out pieces of your string like a pro!
Ahoy there, coding sailors! Prepare to set sail on the high seas of text manipulation with the substrReplace method, a swashbuckling powerhouse hiding within Laravel’s Str class!
Think of it as the pirate parrot of your codebase - repeating, replacing, or even inserting words at will! Just like Jack Sparrow, this method can swap out pieces of strings without causing a mutiny in your code.
To use it, simply call substrReplace and point it towards your string (the first mate). The second argument sets the starting position where the swashbuckling shall commence, and the third argument determines how many characters are to be replaced or inserted (up to ye old limit of 64, matey!).
Setting the third argument to 0 will see ol’ substrReplace inserting the new text without disturbing any of the existing characters. Fear not, for this method is mighty careful when it comes to preserving your original string, just like Blackbeard was with his beard!
So, hoist the main-mast and set sail:
use Illuminate\Support\Str;
$string = Str::of('1300'); // Our trusty ship sets sail on the high seas of numbers
$string->substrReplace(':', 2); // At position 2, we insert a colon. The ship now reads: 13:00!
$string = Str::of('The Framework'); // A new vessel sails from port 'Laravel'
$string->substrReplace(' Laravel', 3, 0); // At position 3, we insert " Laravel" without disturbing the original string. The ship now reads: The Laravel Framework!
Arrrr matey, you’ve mastered the substrReplace method! Now let us see if ye can navigate the treacherous waters of Laravel coding with such agility and precision!
Ahoy there, code pirates! Sail the seas of syntax with me as we dive into Laravel’s swap method, a treasure trove for your textual transformations!
This dashing method, hidden deep within Illuminate\Support\Str, sets sail to replace multiple booty (values) in your string using PHP’s trusty strtr function. Fear not, ye scurvy landlubbers, for I shall walk the plank of explanation to make sure you’re not left hanging (or drowning in jargon).
use Illuminate\Support\Str; // Importing Str like a seasoned sailor does his sea shanty
$string = Str::of('Tacos are great!') // Initializing our string with tasty Tacos
->swap([ // Hoist the anchor and set sail with the swap method
'Tacos' => 'Burritos', // Swap those tasty Tacos for even tastier Burritos
'great' => 'fantastic', // And while we're at it, make great now fantastic
]);
// Burritos are fantastic! // Arrival at our destination: a glorious transformation of text
Fair winds and following seas as you embark on your swaptastic Laravel adventures!
Ahoy there, coding pirate! Sail the seas of PHP with me as we delve into the swashbuckling world of Laravel’s take method! This isn’t your typical “arrrr”-infested treasure map, but it’s just as valuable (and possibly more so) for those seeking a bounty of characters from their strings!
Let’s set sail! First off, you’ll want to hoist the Jolly Roger and import Illuminate\Support\Str:
use Illuminate\Support\Str;
Now, let’s say you’ve captured a string of epic proportions—something like “Build something amazing!”—and you only need the first five letters to make a pirate flag. That’s when our take method comes in handy!
Here’s how you’d use it:
$taken = Str::of('Build something amazing!')->take(5);
// Boom! You've got yourself 'Build'—just what you needed for your pirate flag.
See? Simple as walking the plank (but way less dangerous)! With this newfound knowledge, you can conquer the seas of strings with ease. Yarr, matey!
Ahoy there, Laravel sailors! Sail with me as we dive into the enchanting world of the tap method. You see, this magical spell lets you take a peek at your string and even play a little tune with it, all without leaving any trace of your investigation!
So, let’s say you’ve stumbled upon a mysterious box labeled “Laravel” and want to know what’s inside. But instead of opening it, you’d rather summon a helpful genie (or in this case, a closure) to take a peek for you without spilling its contents. That’s exactly the kind of magic tap brings to the table!
Here’s a fun little example:
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$mysteryBox = Str::of('Laravel')
->append(' Framework') // Adding some mystery to the box contents
->tap(function (Stringable $mysteryBox) { // A helpful genie peeks inside the box
dump('Mysterious Box Contents: '.$mysteryBox);
})
->upper(); // And now, we present... LARAVEL FRAMEWORK!
By using tap, you’ve managed to examine the contents of the mysterious box without altering it and even shared a laugh with your genie friend. Just remember that tap always returns the original string regardless of what the closure decides to share with you. Happy sailing! 🎉
Ahoy there, code wranglers! Let’s dive into the enchanting world of Laravel and cast a spell with our trusty test method! This magical incantation will transform your strings into glorious matches before your very eyes.
use Illuminate\Support\Str;
$wizardry = Str::of('Laravel Framework'); // Cast your string, oh, so elegantly
$result = $wizardry->test('/Laravel/'); // Unleash the spell, and behold!
// If you're lucky enough to witness this spectacle...
// true
Just remember: like all good magic, it requires a touch of precision. Make sure your regular expression pattern is well-crafted and ready for action. Happy coding, dear sorcerers! 🧙♂️✨
Ahoy there, coders! Ever find yourself in a pickle trying to write a snazzy title that’s as elegant as your code? Fear not! Laravel’s title method is here to save the day (and your dignity)!
Just like a well-dressed gentleman, this nifty little helper knows how to make an impression. It takes your string and transforms it into the sophisticated world of Title Case:
use Illuminate\Support\Str;
$spiffyTitle = Str::of('a not so formal title needed some class')->title();
// A Not So Formal Title Needed Some Class
Now, isn’t that swell? Go ahead and wow your peers with your newfound title-tipping skills. And remember, in the grand ballroom of programming, first impressions are everything! 🤵🏽♂️👗
Oh, the toBase64 method! It’s like a secret agent for strings, but instead of spying on international espionage, it’s all about encrypting data in Base64. You can think of it as a fancy translator that speaks ‘Binary’ and ‘Base64’.
Here’s how to call this clandestine operator:
use Illuminate\Support\Str; // Import the Str class from Laravel's support package, which contains our secret agent.
$encrypted_message = Str::of('Laravel')->toBase64(); // Our secret agent is now given a mission to convert 'Laravel' into Base64. And voilà! The encrypted message is TGFyYXZlbA==
And just like that, your ordinary string transforms into an intriguing ciphertext that would give even the toughest hackers a run for their money!
Oh, the toHtmlString method! It’s like a superhero for your strings, transforming them into muscular, rugged specimens of Illuminate\Support\HtmlString. But unlike the Hulk, it won’t destroy your Blade templates – quite the opposite actually. It keeps them safe from unwanted escaping:
use Illuminate\Support\Str;
Transformer Dan here! I've turned 'Nuno Maduro' into a hunk of HTML muscle with just a simple `toHtmlString()`. Isn't that swell? 😉
Just beware, though: this chiseled hunk won’t look so hot if you try to serve it raw. You still need to include it in your Blade templates:
<h1>{{ $htmlString }}</h1>
Happy transforming! 💪🤩
Ahoy there, code pirates! Sail the seas of Laravel with the toUri method, a handy tool that’s about as useful as a cutlass in a sword fight (but without the danger of losing a limb).
This delightful function takes your string and transforms it into a dashing, debonair instance of Illuminate\Support\Uri. Imagine if you will, a shabby street urchin turning into a dashing nobleman at the stroke of a keyboard. Exciting, huh?
Arrr matey! Use ye olde Illuminate\Support\Str:
$uri = Str::of('https://sharkbait_island.com')->toUri();
Now you can navigate the treacherous waters of web URLs with a newfound sense of certainty, knowing that your humble string is now a bona fide instance of URI royalty! Arrghastingly convenient!
Ahoy there, matey! Buckle up for a swashbuckling adventure through the wilds of character conversion with the transliterate method! This dashing technique will do its best to transform your scallywag string into its most respectable ASCII alter ego:
Grab yer compass, ye scurvy dogs! We be sailin' with Str:
$email = Str::of('ⓣⓔⓢⓣ@ⓛⓐⓡⓐⓥⓔⓛ')->transliterate();
// Prepare to be astounded! Ye'll find '[email protected]' at the end of yer journey!
Now, if ye find yourself in need of a cleaner ship (or string), check out the trim method next! Arr matey, this is just the beginning of your Laravel voyage! 🏴☠️🐳🚀
Ahoy there, shipmates! Buckle up for a delightful dive into Laravel’s trim method - the sailor’s best friend in the sea of strings! Unlike Captain Jack Sparrow’s unpredictable trimming habits (he keeps those parrot feathers and pirate peg-leg hair), Laravel’s trim is as reliable as a steadfast compass.
use Illuminate\Support\Str; // Include this, matey!
$string = Str::of(' Arr Matey Laravel ')->trim(); // Behold: 'Arr Matey Laravel' becomes 'Laravel'!
$string = Str::of('/Laravel/')->trim('/'); // Even slash-y paths become slashless, like a pirate ship navigating through shark-infested waters!
Don’t forget that the Laravel trim also has a knack for removing those pesky unicode whitespace characters - a feat even Captain Barbossa couldn’t achieve with his grog-soaked tongue! So set sail, sailor, and let’s make our strings swashbucklingly clean! Yarr!
Alright, strap in, buckle up, and prepare for a rollercoaster ride through the world of Laravel’s ltrim method! This isn’t your average, garden-variety trimming operation. No sirree bob! We’re talking about a high-octane, adrenaline-pumping, left-side extravaganza that will leave your strings leaner and meaner than a Vegas poker champ on a hot streak.
The ltrim method is our hero here, swooping in to remove all the unwanted characters hanging out on the left side of our string. Unlike its PHP cousin, who’s always been a little too vanilla for our taste, Laravel’s ltrim comes with an extra helping of excitement – it can also eliminate those pesky unicode whitespace characters that love to sneak in and ruin your day.
Here’s how you summon this trimming superstar:
use Illuminate\Support\Str;
// First, let's give our string a little too much space on the left side.
$string = Str::of(' Laravel ');
// Now, we call upon the ltrim method to do its magic:
$string->ltrim();
// And voila! Our string now looks like it just stepped out of a high-fashion runway show:
'Laravel '
But wait, there's more! Laravel's `ltrim` can even handle strings that start with slashes, which is like the Wild West of the programming world. Just remember to include the starting slash in your call:
```php
$string = Str::of('/Laravel/');
// And now we ltrim it!
$string->ltrim('/');
// Our string has a newfound sense of direction and purpose:
'Laravel/'
Remember, the `ltrim` method is there for you when you need to keep your strings in tip-top shape. It's like having a personal string stylist who never quits and always keeps things tidy – the ultimate party companion!
Oh, the `rtrim` method! It's like a lint roller for strings in Laravel land. But unlike its PHP cousin that only tackles common string-side grime, our Laravel `rtrim` has superpowers – it can vacuum up those pesky unicode whitespace characters too!
Here's the dance step:
```php
use Illuminate\Support\Str;
$string = Str::of(' Laravel ')->rtrim(); // 'Laravel' – Ta-da! No more pesky spaces on the right!
$string = Str::of('/Laravel/')->rtrim('/'); // '/Laravel' – Now it doesn't end with a forward slash, what a relief!
Just remember to import Illuminate\Support\Str, and this string-sprucing function will work its magic for you!
Ahoy there, brave coder! You’ve just stumbled upon the magical ucfirst method - a veritable elixir for your string concoctions. This isn’t your run-of-the-mill alchemical potion though, oh no! It’s a Laravel brew that returns a given string with its first character as bold and dashing as the Captain’s hat on a pirate ship.
So, let’s raise our anchor, hoist the sails of understanding and set sail for this grand adventure:
use Illuminate\Support\Str;
$string = Str::of('foo bar')->ucfirst();
// Foo bar? More like Foobar in these parts! Arr matey, your strings will never be the same again!
Now, don’t you feel like a swashbuckling master of the Laravel seas? Let your strings dance the jig of courtesy and civility with the ucfirst method. Yarr!
Ahoy there, code wranglers! Sail the seas of PHP with Laravel’s trusty ucsplit method, a swashbuckler of strings if ever there was one. This intrepid pirate splits the string you give it into a collection of treasures, each separated by those pesky uppercase characters that be keepin’ us landlubbers on our toes!
Grab yer ropes, me hearties! Let's summon Str:
use Illuminate\Support\Str;
Set sail with a mighty string: 'Foo Bar'
Now hoist the Jolly Roger of `ucsplit()`: $string = Str::of('Foo Bar')->ucsplit();
In no time, ye'll find yerself swimming in a collect full o' plunder:
// collect(['Foo ', 'Bar'])
Avast, ye’ve got yourself some useful knowledge, matey! Keep hoisting that ucsplit() flag high and beware of any strings laden with capitals; this method will split ‘em like butter! Arr!
Ahoy there, code pirates! Steer clear of the shark-infested waters of string transformations and set sail for calmer programming seas with the ucwords method! This trusty navigator will hoist your Jolly Roger and convert the first letter of each word in your ship’s log (string) to a glorious uppercase!
Ready to parley? Here’s how ye can use it:
use Illuminate\Support\Str;
$parrotSpeak = Str::of('laravel framework')->ucwords();
// "Laravel Framework" will now be your trusty companion on the high seas of coding!
Avast, mateys! Don’t forget to check out more nautical Laravel methods in our swashbuckling documentation! Yarr!
Ahoy there, code swashbucklers! Sail with me into the enchanting world of Laravel strings, where we’ll learn about the swashbuckling unwrap method.
Picture this: You’ve got a string that looks like it’s been pirated - wrapped in unwanted kebab-style brackets or pesky hyphens. Fear not! The unwrap method, our faithful compass, will help navigate through these treacherous waters.
use Illuminate\Support\Str; // Import Str class like a true pirate would hoist his Jolly Roger
// Remove hyphen-like scurvy from the start and end of this string:
Str::of('-Laravel-')->unwrap('-'); // Yarr, now it's just "Laravel"!
// But what if your precious cargo is locked in a chest with curly brackets? Fret not, for `unwrap` can decipher the mysterious {framework: "Laravel"} too:
Str::of('{framework: "Laravel"}')->unwrap('{', '}'); // Hoist the sails high, now it's just "framework: \"Laravel\""!
So hoist those anchor and set sail! With unwrap, you can ensure your strings are as clean and orderly as a well-run pirate ship. Arrrr, be ye ready to conquer the seven seas of Laravel code!
Ahoy there, code wranglers! Let’s shake things up with the upper method, a lively dance of letters that transforms your string into something worthy of a shoutout in a rock concert.
Call in the troops: \Illuminate\Support\Str;
Prepare for an uplifting transformation: $adjusted = Str::of('laravel')->upper();
And just like that, it's a whole new world!
// LARAVEL - It's the new disco hit on the blockchain party scene!
Remember, when your strings are feeling down and need a pick-me-up, reach for the upper method. It’ll have them dancing on the ceiling in no time! 💃🎉
Ahoy there, Laravel coders! Let’s dive into the whimsical world of the when method, a magical incantation that makes your code dance like a pirate at a sea shanty festival.
This enchanting spell casts a condition upon your code, and if it finds itself in a truth-telling mood (or true, to be precise), it invokes the glorious closure you’ve prepared for it. The closure receives the fluent string instance as its captive, ready to be transformed with the power of your PHP prowess.
Use yer trusty compass, Str, and pirate map, Illuminate\Support\Str;
Also grab the ol' parchment, Illuminate\Support\Stringable;
$string = Str::of('Taylor')
->when(true, function (Stringable $string) {
return $string->append(' Otwell'); // Ahoy matey! Yer string just got longer!
});
// 'Taylor Otwell' - our treasure at the end of this journey!
If ye need to prepare for a worst-case scenario, fear not! Ye can pass another closure as the third parameter to the when method. This secondary spell will be cast if the condition evaluates to a fibbing Jack Sparrow (or false, in less piratey terms).
Now, ye might also want to check if yer string contains something. That’s a cinch with the contains method!
$string = Str::of('Taylor Otwell')
->when(fn($string) => $string->contains('Otwell'), function () {
// This spell shall be cast if 'Otwell' is found in yer string.
echo "Found it, matey!";
})
->when(!fn($string) => $string->contains('Captain Hook'), function () {
// This other spell shall be cast if 'Captain Hook' isn't found in yer string.
echo "No sign of Captain Hook here.";
});
// Echoes: Found it, matey!
Yarr, that’s the when method in a nutshell! Happy pirating!
Alright, strap on your coding aprons, folks! Today we’re going to delve into the charmingly named whenContains method - a chameleon of a function in the Laravel world.
Imagine you’ve got a string as fancy as Tony Stark himself and you want to give it a little title makeover when it mentions its own namesake. Well, that’s where our humble friend whenContains comes into play!
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('tony stark')
->whenContains('tony', function (Stringable $string) {
// It's a bird, it's a plane... no wait, it's TONY!
return $string->title();
});
// 'Tony Stark'
But what if our string is more of an Avengers-sized party and we want to ensure everyone gets a title upgrade when they show up? No problemo! Just pass an array of values to our trusty whenContains.
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('tony stark hulk black widow')
->whenContains(['tony', 'hulk'], function (Stringable $string) {
// Avengers, assemble!
return $string->title();
});
// Tony Stark, Hulk, Black Widow
Now that’s some superhero-level string manipulation, my friends! Just remember, if you need to apply a different closure when the string does not contain the given value, simply pass another closure as the third parameter.
Happy coding, and may all your strings be titled! 🎉🥂🚀
Ahoy there, Laravel pirate! Ever wanted to turn a plain ol’ string into something swashbucklingly splendid? Meet your new best friend: whenContainsAll – the method that’s as cunning as Captain Jack Sparrow and just as essential on your coding voyage!
Set sail with this enchanting piece of code, mateys:
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('tony stark')
->whenContainsAll(['tony', 'stark'], function (Stringable $string) {
return $string->title(); // Arrr! Titled like a true gentleman
});
// 'Tony Stark' – fancy that, a proper greeting for the Iron Man himself!
But what happens when your string is more slippery than an eel and you need a backup plan? Fear not, ye scurvy dogs, for whenContainsAll allows ye to set another closure as the third parameter. This second-in-command will be summoned if the main condition fails:
// If 'tony stark' doesn't contain 'iron man', let's throw in a little taunt!
$string = Str::of('tony stark')
->whenContainsAll(['tony', 'stark'], function (Stringable $string) {
return $string->title(); // Arrr! Titled like a true gentleman
}, function () {
return "Oh no, where's Tony Stark's Iron Man suit?"; // A bit of humor when things go awry
});
Now, off you sail with your newfound knowledge and unleash the power of whenContainsAll – may it serve ye well on your code-writing escapades!
Alright, let’s get this string party started! 🎉🎈
Introducing the whenDoesntEndWith superhero in your Laravel toolkit! This dashing method swoops in to save the day when your string just can’t seem to decide where it wants to stop. 🤔🛑
In plain English, if your string isn’t ending with a certain sub-string (like a rogue ‘land’ invading your ‘disney world’), whenDoesntEndWith will summon the power of your provided closure!
Here’s what it looks like in action:
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('disney world')->whenDoesntEndWith('land', function (Stringable $string) {
return $string->title(); // Ta-da! 'Disney World' to the rescue! 🏆🌐
});
So, go ahead and unleash this string ninja in your Laravel adventures. With whenDoesntEndWith, you can ensure a tidy ending for all your strings, even when things get a bit messy. 🧹🥳
Ah, the whenDoesntStartWith method! It’s like a superpower for strings, but without the spandex. This magical function lets your string do a little dance if it doesn’t start with a specific substring you choose to torment it with.
Imagine you have a string that goes “disney world” and you want to yell at it if it doesn’t start with “sea.” No problemo, amigo! Just call in the cavalry (aka Laravel) and they’ll take care of the rest.
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('disney world')->whenDoesntStartWith('sea', function (Stringable $string) {
// This is where you unleash your string wrath!
return $string->title();
});
// 'Disney World' (the poor string is being capitalized as punishment!)
So, go on and let your strings feel the Laravel love. But remember, with great power comes great responsibility… or something like that.
Ah, the whenEmpty method! It’s like the fun-loving, party-starting cousin of your string in Laravel land. If your string is found empty-handed at a social event (aka when it’s empty), this charming fellow will introduce it to the life of the party – a magical closure that you provide!
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of(' ')->trim()->whenEmpty(function (Stringable $string) {
return $string->prepend('Laravel'); // A glamorous makeover for an empty string!
});
// And voila! 'Laravel' – the life of the party, ready to rock on!
Just like a hilarious stand-up comedian who only shines when the audience is silent, whenEmpty comes into play when your string needs a bit of help to keep the conversation going. And remember, if that witty closure doesn’t crack a joke and returns nothing, your string can still save the day by keeping its original flair! 😄
Oh, the whenNotEmpty method! It’s like the life of the party for your strings in Laravel land. This little dance partner only gets up when your string isn’t empty and has a bit too much to drink (in a good way). 🥳
If this gregarious guest manages to find a dance partner (your string), it insists on leading the two of them into a secret rendezvous with the closure you provided. If your closure returns something, well, then your whenNotEmpty method will proudly strut back out with that fancy return as its new dance partner! 💃🕺
But if your closure is shy and can’t find anything to say, the original stringable instance won’t feel left out and will simply continue dancing the night away with the other strings. 🌟
So, let’s dance!
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('Framework')->whenNotEmpty(function (Stringable $string) {
return $string->prepend('Laravel ');
});
// 'Laravel Framework' - That's quite the rhythm, isn't it? 🎶
Now that you know how to twirl with this method, let’s keep the party going! 🎉🥳
Ahoy there, coders! Buckle up for a rollercoaster ride through the magical lands of Laravel string manipulation. Today, we’re going to talk about the enchanting whenStartsWith method, a spell that will make your code dance like Mickey Mouse on his birthday!
This bewitching incantation summons the power of a closure when a specific sub-string sets the story in motion. Picture it: you’ve captured the string ‘disney world’ in a bottle and now you’re ready to unleash its magic with just a sprinkle of whenStartsWith.
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('disney world'); // Capture that dazzling string!
$string->whenStartsWith('disney', function (Stringable $string) { // Call the right spellcaster for the job!
return $string->title(); // Transform 'disney world' into 'Disney World'!
});
And just like that, your string has been transformed from a commonplace “disney world” into the majestic “Disney World”. Now go forth and conquer your codebase with this magical method! After all, who doesn’t want to write code as charming as a Disney prince or princess? 👰🏼♀️🤵🏻♂️✨
Ah, the whenEndsWith method! A cunning little trick up Laravel’s digital sleeve. It’s like having a magical genie that grants you wishes based on whether your string ends with a specific sub-string.
Imagine you’re in a wild west saloon, and you’ve just ordered a ‘whisky world’. If the bartender hands you a drink with ‘world’ at the end, this method is your new best friend! It will trigger a clever little closure, making your ‘whisky world’ become the ‘Whisky World’, all while keeping its spirit intact.
Here’s how it works:
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$drink = Str::of('whisky world'); // We've got a 'whisky world', but we want a 'Whisky World'!
// Call our magical genie, and if the 'world' is present at the end...
$drink->whenEndsWith('world', function (Stringable $drink) {
// ...make it fancy by capitalizing its name!
return $drink->title();
});
// And lo and behold, we have our 'Whisky World'!
Now that’s what I call a fun little dance in the world of strings!
Ah, the whenExactly method! It’s like a picky date for your strings, only instead of roses and chocolates, it’s all about precision. This suave gentleman will only call your closure if the string is, well… exactly the one you asked for. No mix-ups, no misunderstandings, just pure string-on-string compatibility!
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$boyfriend = Str::of('laravel')->whenExactly('laravel', function (Stringable $boyfriend) {
return $boyfriend->title();
});
// 'Laravel' - Now isn't that a charming gentleman!
Just remember, this is a one-night stand kind of method. It doesn’t chain with other methods like a good boy should. But hey, who said life was fair? Just enjoy the moment and move on when you need to!
Ah, the whenNotExactly method! It’s like the anti-matchmaker of Laravel strings. Instead of pairing up perfectly like Romeo and Juliet, it sets up a blind date between a string and a closure when they don’t hit it off right away (read: match exactly).
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('framework')->whenNotExactly('laravel', function (Stringable $string) {
return $string->title();
});
// 'Framework' is the name of the date, because let's face it, 'framework' and 'laravel' just weren't feeling each other!
Now, don’t go getting any ideas about love stories in your code, but this method can be quite useful for cleaning up string cases or adding prefixes and suffixes without having to write a whole bunch of if statements. Just remember, it’s all in the name of organization and keeping your PHP heart warm! 💖💻
Ahoy there, matey! Prepare to set sail on the high seas of Laravel with the whenIs method - a swashbuckling helper that sets off an adventure if your string matches a dashing pattern!
Remember those treasure maps from Pirates of the Caribbean? Imagine you’ve got one, but instead of X marks the spot, it says “foo/*”. And as Captain Jack would say, “Ye be lookin’ for ‘foo’ and any ol’ thing that follows!”
Just like in the movies, our whenIs method doesn’t disappoint. It calls a clever closure (a pirate’s trusty parrot in this analogy), and your closure gets to board the ship with the fluent string instance as its new companion!
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('foo/bar'); // Setting off on a voyage with 'foo/bar'
$string = $string->whenIs('foo/*', function (Stringable $string) {
return $string->append('/baz');
});
// Treasure uncovered! Hoist the anchor, matey! We now have 'foo/bar/baz'
And don’t worry about getting lost at sea – with whenIs, you’re always in control and ready to set a course for adventure whenever your string matches its pattern!
Ahoy there, coder! Dive into the delightful world of Laravel strings with the whenIsAscii method, a quirky little helper that’ll tickle your technical taste buds. 🍔🌮
This charming fellow checks if your string is as simple as an old-school ASCII cat meme (7 bits of pure, unadulterated joy). If it is, it fires up the given closure—but wait, there’s more! The lucky recipient of this flamboyant flair? None other than your beloved fluent string instance. 🤩
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('laravel')->whenIsAscii(function (Stringable $string) {
return $string->title();
});
// 'Laravel' - ta-da! Your string's been promoted to a respectable title.
So, let’s give this whimsical wonder a spin and add some pizzazz to your codebase—your strings will thank you for it! 🥳
Ahoy there, Laravel pirates! Let’s set sail into the choppy waters of methodology with whenIsUlid, shall we? This sea shanty of a function is here to make your codewalk a tad more jolly and less salty.
If you happen upon a string that resembles a ULID (Universally Unique Lexicographically Sortable Identifier, yarr), whenIsUlid will hoist the Jolly Roger and let fly the function you’ve provided! This buccaneer of a closure will be greeted with your fluent string instance like old friends greeting each other on a far-off island.
use Illuminate\Support\Str;
$parrotString = Str::of('01gd6r360bp37zj17nxb55yv40');
$parrotString->whenIsUlid(function (Stringable $string) {
return $string->substr(0, 8); // '01gd6r36'
});
Now, you’ve got yourself a tidy little substring from the ULID, enough to stick on your peg-leg compass and chart a new course. Ah, the joys of seafaring code!
Ahoy there! Buckle up, code cowboys and cowgirls! Let’s dive into the wild west of Laravel land with a method as mighty as a grizzled prospector’s pickaxe - whenIsUuid!
This here method is a wrangler for your strings, ensuring they’re as legitimate as a gold nugget in California. If your string is a bona fide UUID (Universally Unique Identifier), it’ll unleash the might of a closure upon it. The closure, you ask? It’s a trusty sidekick that’ll receive a fluent string instance as its deputy.
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('a0a2a2d2-0b87-4a18-83f2-2529882be2de')->whenIsUuid(function (Stringable $string) {
return $string->substr(0, 8);
});
// 'a0a2a2d2'
In this here example, our UUID string gets its first 8 characters chopped off quicker than you can say “Yeehaw!” - it’s as slick as a greased coyote. So, saddle up and lasso the whenIsUuid method for all your string-wrangling needs!
Alright, folks! Buckle up for a whirlwind tour of Laravel’s whenTest method. This ain’t your grandma’s regex dance party – it’s a sophisticated string match shindig that’ll make your code groove to the beat of functional elegance!
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('laravel framework')->whenTest('/laravel/', function (Stringable $string) {
return $string->title();
});
In this example, our string is ‘laravel framework’ – a veritable symphony of letters just waiting to be transformed. We’re using Laravel’s very own Str::of() function to create a new string instance, and then we’re inviting the whenTest method to join the party.
The whenTest method is like that cool bouncer at the club – it only lets in those strings that match its regular expression. In our case, it checks if ‘laravel’ is found within the string. If so, the fun begins!
The function we’ve passed as an argument to whenTest is like a secret sauce for our string. It receives the fluent string instance as a parameter – a sophisticated dance partner that knows all the moves. In this case, it performs the title() method on the string, capitalizing the first letter of each word and returning ‘Laravel Framework’.
So there you have it! The whenTest method is like bringing your own bouncer to the party – guaranteeing that only the right strings get in, and serving them up with a little style. Now go out there and make your code dance to its own tune with this fantastic Laravel feature! 💃🏼🕺🏼🚀
Ahoy there, coding pirates! Set sail for the shores of phrasal analytics with the wordCount method, a buccaneer’s best friend when it comes to counting the number of words in your seafaring yarns!
use Illuminate\Support\Str; // Don your nautical hat and grab the helm
Str::of('Hello, world!')->wordCount(); // Yo ho ho, ye words be two!
Now you can keep track of how many parrots are perched on each shoulder while sharing your tales of the sea with your shipmates. Fair winds and following seas! 🦭🌬️⚓️
Ahoy there, coding sailors! Ever found yourself in a pickle trying to tame the verbosity of old Captain Longwinds’ ramblings? Fret not, for we’ve got just the thing you need – the words method!
This swashbuckling technique will ensure that your string never overstays its welcome and leaves a charming trail of intrigue behind. To use it, cast a spell on your string with Str::of(), then command words() to keep only the first three hearty pirate words:
use Illuminate\Support\Str;
$string = Str::of('Perfectly balanced, as all things should be.')->words(3, ' >>>');
// Hoist the Jolly Roger! Now, you'll find our intrepid hero sailing a shorter, yet still enticing, course: Perfectly balanced, as >>>
Remember, ye scurvy dogs, if ye desire more than three words to be included in your string, simply adjust the number accordingly. Happy pirating! 🏴☠️⚔️🌴
Ahoy there, coders! Sail into the shores of Laravel’s enchanting Str class and prepare to be dazzled by the wrap method - a pirate-worthy tool that’ll have your strings walking the plank with style!
Imagine, if you will, you’ve stumbled upon a treasure chest full of raw string data, but it needs a bit o’ polishing. Enter the wrap method, your trusty cutlass to transform those unruly strings into a well-behaved pirate crew!
use Illuminate\Support\Str;
// A simple case: turn "Laravel" into a quotable quote
$treasure = Str::of('Laravel');
$quotes = "'";
$quotedTreasure = $treasure->wrap($quotes); // Voila! "Laravel"
// Swab the decks with more style: wrap "is" before "This " and after " Laravel!"
$parrotSpeech = Str::is('is');
$before = 'This ';
$after = ' Laravel!';
$quotedParrotSpeech = $parrotSpeech->wrap(before: $before, after: $after); // This is Laravel!
So, hoist the Jolly Roger high and let’s set sail on this enchanting journey with the wrap method! Your strings will be cleaner than Captain Jack Sparrow’s parrot, Polly!