Search code examples
phpstringmarkdownsubstrstrpos

Need a scalable way to Limit Content by using substr() and strpos() in PHP


I am using Markdown to render a rich content on a page, using PHP. For the brief version, I think it would be fine to truncate the content till second paragraph, or technically, after two \r\n have crossed. So I used this code:

substr($content, 0, strpos($content, "\r\n\r\n", strpos($content, "\r\n\r\n") + 1));

Since the count of \r\n is hard coded, and is also calculated in a weird way, (using +1 after the first position and stuff), is there a better way I can make a function, which says limitContent($content, $lines = 2) and passing the number of lines to the $lines parameter, as by default, it truncates to two lines?

My current code is:

/**
 * Break down the content of Markdown upto 2 breaks. 
 * @param string Markdown String
 * @return string Markdown String upto 2 breaks
 */
function limitContent($content)
{
    return substr($content, 0, strpos($content, "\r\n\r\n", strpos($content, "\r\n\r\n") + 1));
}

Thanks in advance.


Solution

  • Ok, I misunderstood. Is this what you want?

    function limitContent($content, $lines=2)
    {
        $tmp=explode("\r\n\r\n", $content);
        $tmp=array_slice($tmp,0,$lines);
        return implode("\r\n", $tmp);
    }
    

    [edit] And slightly better would be:

    function limitContent($content, $lines=2)
        {
            $tmp=explode("\r\n\r\n", $content, $lines+1);
            unset($tmp[$lines]);
            return implode("\r\n", $tmp);
        }