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:
$product_name
= the name of the product - like MacBook Pro - 11$product_brand
= the name of the brand - like Apple - 5$product_action
= the name of the product - buy online - 9$product_store
= the name of the product - on Storename - 9Combined 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.
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);