This looks like the following function: $first_part_of_string = mb_strimwidth($string, 0, 30, '.') įor our specific example, we want to return the excerpt of an article description. In order to go from the start of the string to the following 30 characters, you need to replace int $start with 0 and replace int $width with 30. A code example that they provide is visible below: mb_strimwidth ( string $str, int $start, int $width ] ) : string Per PHP’s documentation, the mb_strimwidth function allows you to get a truncated string with a specified width. This is listed as the second option because I don’t use it as regularly as I use the substr when I code, but it’s just as easy to use. this generates the following string - This article is all about gett.Ī second way to return the first characters of a string in PHP is to use the mb_strimwidth function. We show you different PHP functions that get you there as quickly as possible. As you see below, I prefer to trim the description before running it through substr so that the result won’t have spaces at the beginning or end and I want to add an ellipsis at the end so my users know that there is more to read: $description = 'This article is all about getting the first part of a string in PHP. $first_part_of_string = substr($string,0,30) įor example, in order to get the first 30 characters of our article description, we would run the following code. So, in the function below, 0 is the position where you want to start from and 30 is the number of characters that you would like to show from the start of the string. The code example they provide is listed below: substr ( string $string, int $start ) : string ![]() Per PHP’s documentation, the substr function allows you to return part of a string. Therefore, substr is my preferred method of getting the first characters of a string in PHP. ![]() ![]() To me, the easiest option is to use PHP’s substr function. For example, let’s say we have a description of an article but we want to trim it down to the first 30 characters to generate an excerpt. There are two primary ways to get the first characters of a string in PHP.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |