Add a WordPress-like Read More link to your content

Today I am going to show you how to write your own function which shows teaser text with a “Read more” link. It may not be the best way but it pretty does the intended functionality.

The logic is pretty simple:
Add <!--more--> HTML commented text as it is, any where in the full text. The text before this comment will be displayed as the teaser.
Call the readMore function with the full text and the URL to the full text as parameters.
Lets do it!
First, we are going to write the function. Lets call it readMore, which takes three parameters:

The first line of the function, the $pattern variable contains a Regular Expression (RegEx) which identifies an HTML comment tag with the text “more”. Then I called the PHP’s RegEx version of the split function preg_split which takes a RegEx pattern and the text to apply the pattern to, as parameters and returns an array. the first element (element at index 0) in the resulted array is the teaser of the full text we passed as parameter. Then, return the teaser with a link to the full text. We can give any label we want, instead of “Read more” just pass a string as the third parameter.