I have this function which cuts a string into a number of characters without chopping any word. I use it for the meta_description of a page.
function meta_description_function($text, $length){ // Meta Description Function
if(strlen($text) > $length) {
$text = substr($text, 0, strpos($text, ' ', $length));
}
return $text;
}
I pull the content from a wordpress post:
$content = $content_post->post_content;
I strip the tags from the content:
$content = strip_tags($content);
And I aplly my function to the content:
$meta_description = meta_description_function($content, 140);
The problem is when the $content is like this:
<p>Hello I am sentence one inside my own paragraph.</p>
<p>Hello I am sentence two inside my own paragraph.</p>
After applying the content and I echo $meta_description I get the sentences in different lines, something like this:
<meta name="description" content="Hello I am sentence one inside my own paragraph.
**<i get a space here!>**
Hello I am sentence two inside my own paragraph." />
Why does this empty space appear if I have used strip tags, what can I do to make it disappear?
trim the whitespace, and remove line breaks. then strip the tags. all in one line!
$content = trim( preg_replace( '/\s+/', ' ', strip_tags($content) ) );Note: \s takes care of a few more cases than just line breaks and spaces.. also tabs and form feeds, etc.DEMO