Page 1 of 1

Counting String and adding '...' if String is greater than $

Posted: Thu Jan 29, 2009 12:56 pm
by Zehna
Hi everyone! Nice to meet you.

I'm having some trouble figuring out how to do this.

I'm creating a variable called $review from my database. I am using the substr function (function, right?) to not pull more characters than 1417. If the variable equals exactly 1417 characters, I want to create a variable called $more which is equal to "...". The variable called more will be echoed after the $review variable to signify that there is still more review. This will tell the user to click on the link to see the full page and read the whole review.

Unfortunately, it sounded easy... but I can't figure out how to make that work! I've tried using the 'count' function and the 'strlen' function to count the characters and if it is equal to 1417 to create the variable 'more'. I haven't been able to make this work, though.

Any help would be greatly appreciated! Thanks so much~

The website that I want to do this to can be found here: http://zehnaart.com/imp It is the index page that I am doing this to. The "Hot Topic" movie is the review that I am looking to do this to.

Re: Counting String and adding '...' if String is greater than $

Posted: Thu Jan 29, 2009 3:04 pm
by VladSun

Code: Select all

$fulltext = 'full text here';
echo substr($fulltext, 0, 1417).(strlen($fulltext) > 1417 ? ' ...' : '');

Re: Counting String and adding '...' if String is greater than $

Posted: Thu Jan 29, 2009 4:10 pm
by Zehna
AH!! It works PERFECTLY, thank you!! :D

I understand the functions but I'm not too sure about the way it's laid out. Could you please explain this part to me?

Code: Select all

(strlen($fulltext) > 1417 ? ' ...' : '')
I'm not sure why everything is placed in parenthesis. The second pair containing the $fulltext I understand, but not why there are ones before strlen and after the ". I was only aware you used parenthesis with functions, but doesn't the '.' mean you are concatenating something? (Is that the right word? Maybe I'm thinking Flash terms?)

Also... What does the '?' symbolize, as well as the ':'? I am not sure what they stand for in the code. Is the '?' an "if" and the ':' and "else"?

Thanks so much for your help! :D

Re: Counting String and adding '...' if String is greater than $

Posted: Thu Jan 29, 2009 4:16 pm
by VladSun
It's called "ternary operator" - a flow control operator.

http://php.codenewbie.com/articles/php/ ... age_1.html

Re: Counting String and adding '...' if String is greater than $

Posted: Thu Jan 29, 2009 4:34 pm
by Zehna
Oh, awesome! Thanks so much! :D