How to trim entire words from php string
like I dont want "foo"
, "bar"
, "mouse"
words on left and "killed"
on the end of string.
So "fo awesome illed"
would not
be trimmed
But "foo awesome killed"
=> " awesome "
"killed awesome foo"
not trimmed (killed trimmed from right, rest from left)
When I'm using ltrim($str, "foo")
; it will trim any letter from "foo"
- "f"
or "o"
The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string. rtrim() - Removes whitespace or other predefined characters from the right side of a string.
function limit_text($text, $limit) { if (str_word_count($text, 0) > $limit) { $words = str_word_count($text, 2); $pos = array_keys($words); $text = substr($text, 0, $pos[$limit]) . '...'; } return $text; } echo limit_text('Hello here is a long sentence that will be truncated by the', 5);
PHP: substr() function The substr() function used to cut a part of a string from a string, starting at a specified position. The input string. Refers to the position of the string to start cutting. A positive number : Start at the specified position in the string.
The second one involves trimming strings based on how many characters we want to remove from either end. There are three different trimming functions in PHP called ltrim (), rtrim (), and trim (). They remove either whitespace or any other set of characters from the left end, right end, or both ends respectively.
The first one involves removing specific characters from either one or both ends of a string. The second one involves trimming strings based on how many characters we want to remove from either end. There are three different trimming functions in PHP called ltrim (), rtrim (), and trim ().
Just like trimming a specific set of characters, PHP also has dedicated functions to trim a specific number of characters. The substr ($string, $offset, $length) function is best suited for this job. It accepts three parameters and returns a substring. The first parameter is the string you want to trim.
PHP trim is an inbuilt function in PHP. It removes whitespaces (or other characters) from both the left and right sides of a string. In this article, we will discuss the PHP trim Function.
Use preg_replace()
to replace the strings with an empty string.
$str = preg_replace('/^(foo|bar|mouse)|killed$/', '', $str);
Go to regular-expressions.info to learn more about regexp.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With