How to Make Read More Link from String in PHP?

By Hardik Savani May 14, 2024 Category : PHP

We may require to make read more function in core php project. read more link require to create when you have long text or string and limited space to display that text at that time we need to make read more link after some words or character.

Here, in this example you will learn how to make read more link after specific character length. if you require after some text read more button or '...', that way user can click on it and see more details from there. So here you can do it using php substr().

PHP substr() through we will get specific character from string and return with read more link. In this example i make single function to display read more link after some character, you can pass specific character like 100, 200, 500, 1000 etc.

So, let's see bellow example and check readMoreHelper() function.

index.php

<?php


$longString = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod

tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,

quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo

consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse

cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non

proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";


echo readMoreHelper($longString);


function readMoreHelper($story_desc, $chars = 100) {

$story_desc = substr($story_desc,0,$chars);

$story_desc = substr($story_desc,0,strrpos($story_desc,' '));

$story_desc = $story_desc." <a href='#'>Read More...</a>";

return $story_desc;

}


?>

You can simple copy above file code and run in your local, you cal also add link path by passing argument.

I hope it can help you.

Tags :
Shares