3

I am creating some code to auto-generate a meta-desc for product pages in VM.

I have stripped tags, but I am still seeing &nbsp in the resulting text.

The code I have at present is:

if ($product->metadesc) {
    $document->setDescription($product->metadesc);
} else {
    $document->setDescription(strip_tags("Buy ".$category->category_name." | ".$product->product_name." | ".$product->product_desc));
}

So for example, this produces:

Buy T-Shirts | PTB Keep Calm | PTB Keep Calm This creative design is printed  on a Premium Fitted CVC Crew Tee  Features:60% combed rin...

Is there anything I can do to remove these non-breaking space entities?

1
  • 1
    Try $document->setDescription(strip_tags(html_entity_decode("Buy ".$category->category_name." | ".$product->product_name." | ".$product->product_desc)));
    – Lodder
    Aug 6, 2018 at 15:15

1 Answer 1

3

html_entity_decode(), as suggested by Lodder, is a suitable function call. If you wish to "mop up" consecutive spaces, a simple, broad sweeping regex call will do the trick.

*I have added the unicode pattern modifier for maximum replacement coverage.

Demo:

$category = new stdClass();
$category->category_name = 'T-Shirts';
$product = new stdClass();
$product->product_name = 'PTB Keep Calm';
$product->product_desc = 'PTB Keep Calm This creative design is printed  on a Premium Fitted CVC Crew Tee  Features:60% combed rin...';

$decoded = strip_tags(html_entity_decode("Buy " . $category->category_name." | ".$product->product_name." | ".$product->product_desc));
echo $decoded;

echo "\n---\n";

echo preg_replace('~\s+~u', ' ', $decoded);

Output:

Buy T-Shirts | PTB Keep Calm | PTB Keep Calm This creative design is printed  on a Premium Fitted CVC Crew Tee  Features:60% combed rin...
---
Buy T-Shirts | PTB Keep Calm | PTB Keep Calm This creative design is printed on a Premium Fitted CVC Crew Tee Features:60% combed rin...

Of course, if you don't have any other entities to decode and you want to condense spaces, you could just use regex.

echo preg_replace('~(?:\s| )+~u', ' ', strip_tags("Buy " . $category->category_name." | ".$product->product_name." | ".$product->product_desc));
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.