Cray
Cray

Reputation: 5483

PHP: Split string based on its length

I'm using 4 parts to build a meta title from my content. Now I want to limit the meta title to 55 characters and cut parts from the title. But I don't want to cut inside a word. Instead I want to check the length of the title and delete parts from the end until the whole title is under the limit of 55 again.

I'm using the following parts for example:

Combined these are 41 characters. So everything is fine.

But if I have something like this (75 characters):

Surface Pro X black 64 GB, 512 GB 5G/Wifi Microsoft buy online on Storename

I want to reduce it to this:

Surface Pro X black 64 GB, 512 GB 5G/Wifi Microsoft

Because that's the title with under 55 characters. I removed product_action and product_store.

At the moment I'm using a combined string and count the characters:

$product_title          = $product_name.' '.$product_brand.' '.$product_action.' '.$product_store;
$product_title_count    = strlen($product_title);

Is there an intelligent way to generate a title like that? At the moment I'm using an if/else statement which doesn't work well.

Upvotes: 0

Views: 133

Answers (2)

Agnohendrix
Agnohendrix

Reputation: 610

This should go, it will trim your string at the nearest space character(' ') under 55 characters length.

$i = strlen($product_title)-1;
while($product_title[$i] != ' ' || $i > 55){
    $i--;
}
$final_string = substr($product_title, 0, $i);

Upvotes: 2

Salmane Ait Moudoud
Salmane Ait Moudoud

Reputation: 468

put this before @Agnohendrix 's code

$product_title          = $product_name.' '.$product_brand.' '.$product_action.' '.$product_store;
$product_title_count    = strlen($product_title);

if($product_title_count > 55){
    $product_title          = $product_name.' '.$product_brand.' '.$product_action;
    $product_title_count    = strlen($product_title);
}
elseif($product_title_count > 55){
    $product_title          = $product_name.' '.$product_brand;
}

Upvotes: 1

Related Questions