0

I have a few variables set, example:

$url = 'http://stackoverflow.com'; $tag1 = '#lorem1'; $tag2 = '#lorem2'; $tag3 = '#lorem3'; $tag4 = '#lorem4'; $tag5 = '#lorem5'; 

I want to put them all together into a string. Something like this:

$final = $url .' '. $tag1 .' '. $tag2... 

However, if the $final string will exceed 140 characters, then do not add variable.

So for example, if $final string is 137 characters, then do not add $tag5 into joined variable string because its value will make it exceed 140 characters.

How can I do this?

3 Answers 3

2

You'll have to code a simple loop like this:

$str = ''; foreach($parts as $part) { if(strlen($str.$part) >= 140) { break; } $str .= $part; } return $str; 

This is pretty much the only way to do this IMO.

Sign up to request clarification or add additional context in comments.

3 Comments

You'll have to put your "tags" into an array for this to work
To confirm, I need to put all variables in an array named $parts in order for this to work?
Very nice, works great. I will accept in one moment.
0

LET suppose u made $array_name_str which store all the strings u mentioned.

$nb_input = 0; $final_str = ''; foreach($array_name_str ad $row) { $length_curr_str = strlen($row); if( $length_curr_str > (140 - $nb_input)) break; // We add the curr string $final_str .= $row; $final_str .= " "; // Updating size of output str $nb_input += $length_curr_str; } return $final_str; 

Comments

0

Here with limit option that could be used anytime by any condition;

function to_tag(array $tags, $limit = 140) { $str = ''; foreach ($tags as $tag) { $str .= ' '. trim($tag); if (strlen($str) > $limit) { $str = substr($str, 0, strrpos($str, ' ')); break; } } return trim($str); } print_r(to_tag(['foo1', 'foo2', 'foo3'], 10)); // foo1 foo2 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.