Angga Cuacua Angga Cuacua - 29 days ago 8
PHP Question

How can I only get the string from array that contains images using substr function

I try to cut a string from array to a specified length with PHP

substr()
function, but my problem is, in some cases, that array only contains images with no single string content on it.

My code:

<div class="ct f-light">
<?php
$num_char = 255;
$text = $in['content'];
echo substr($text, 0, $num_char) . '...';
?>
</div>


$in['content']
is an html. it was processed from CKEditor whichs contain both text and images.

This is the result if the array only contains a string:

enter image description here

and this is the result if it only contains images :

enter image description here

How can I solve this?

Answer Source

What does your $in['content'] look like? Is it in html? Or how did you mix images and text?

If you have that, I would suggest separating them. (into different variables) This would be the cleanest option. Alternatively, you can also search for the first image tag and then only use the text before that, like this:

$num_char = 255;
$text = explode('<img', $in['content'], 2)[0];
echo substr($text, 0, $num_char) . '...';

You then might also want to check for an empty string.

If you are not using html, please clarify what you are using.

(Also, in case you didn't notice, tags like <p> will count towards the 255 character limit, so there will most likely be less than 255 characters visible. Also this might result in bad (incomplete) html.)