J.me

Limit string using regex with PHP

Sometime, we want to limit our string to display only few from the whole string. For example, in the homepage. This can be archieved easily using the default substr function. The example of the usage to limit to 25 characters:

<?php
    $string = “This is example string. Read it and forget it.”;
    echo substr($string, 0, 25);
?>

The result is

This is example string. R

Hmm… Not good… The string break in the middle of word and the string looks bad. Isn’t it better if we break it in the end of the word? So the result we want is

This is example string. Read

But how to do that? The answer is simply by using Regular Expression (regex). PHP provide two sets of regex functions, the POSIX Extended Regular Expressions and PCRE (Perl-Compatible Regular Expression). In this article, we will use the PCRE one.

The regex we will use is this

/^(.{1,25}[^\s]*).*$/s

Let’s see it in action

<?php
    $string = “This is example string. Read it and forget it.”;
    $reg = “/^(.{1,25}[^\s]*).*$/s”;
    echo preg_replace($reg, “\\1”, $string);
?>

The result is

This is example string. Read

Yeah, that’s it! And now a little description of how it works.

First the both / (slash) in the begining and end is the default syntax for Perl regex. We can however, change it to another unique character.  For example @. The finishing s means it needs to also match newline character. Now let’s take a look on the regex, we begin with ^ which means we want to match from the start of string. The (.{1,25}[^\s]*) do the trick. The enclosed brackets will group this matched string, then we can later use it using \\1. Now see the .{1,25}, this will match any characters from 1 to 25, so it stop match in the 25th characters. The [^\s]* will match any character except whitespace. So after we match until the 25th character, it then match any characters until the whitespace occured, which means, until the end of the word. 🙂 Now the rest .*$ just to match until the end of string, so when we use preg_replace, we can get the first group and delete the rest.

Hmm… But isn’t it better if we create our own function for this? Yep, here it is.

<?php
function limit_the_string($string, $limit)
{
    if (strlen($string) < $limit) // if the limit is more than the string length, we will do nothing and return the whole string
        return $string;
    $reg =”/^(.{1,” . $limit . “}[^\s]*).*$/s”;
    return preg_replace($reg, ‘\\1’, $string);
}
?>

And the usage

<?php
    $string = “This is example string. Read it and forget it.”;
    echo limit_the_string($string, 25);
?>

Well done… Thanks for reading. 🙂

10 comments | Leave a comment

Reply to George Garchagudashvili Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.