ihprince's avatar

How to divide string as per requirement?

Suppose, In database, I have a table where column name is title & description.

In the title column, I stored data as "Welcome To Our Ecommerce Shop"

Now, I want to display that in frontend like this

 <p> Welcome to Welcome To Our Ecommerce </p>
<h1> Shop </h1>

In the description column, I stored data as "Description is the pattern of narrative development that aims to make vivid a place, object, character, or group.Description is one of four rhetorical modes, along with exposition, argumentation, and narration. In practice"

Now, I want to display that in frontend like this

 <p> Description is the pattern of narrative development that aims to make vivid a place, object, character, or group</p>
<h1> Description is one of four rhetorical modes, along with exposition, argumentation, and narration. In practice</h1>

How can I divide a string & display them in my desired design format?

0 likes
4 replies
chaudigv's avatar

This is how I would do it. Split the string by space.

$descArray = explode(' ', $description);

Then I would chunk and loop through.

$sentenceLimit = 20;

foreach(array_chunk($descArray, $sentenceLimit) as $line) {
    echo "<p>" . implode(' ', $line) . "</p>";
}
automica's avatar

@chaudigv you won’t get the OPs result if you split on space.

It looks like @ihprince is wants to split up several sentences which would mean you should explode on a full stop.

Given how unclear this is, I would recommend adding separate columns for title and description.

Semantically though you would output h1 before any p tags as h1 has higher page rank.

Snapey's avatar

I assume these are non-sensical replacements for the real thing.

The problem with your question is that you don't provide any rules as to how these strings should be split

martinbean's avatar

@ihprince You’ve just shown two arbitrary strings and said you want split them in arbitrary positions.

If you can’t come up with the rules on when to “split”, then we can’t either.

Please or to participate in this conversation.