tags:

views:

112

answers:

4

If a user types a really long string it doesn't move onto a 2nd line and will break a page on my site. How do I take that string and remove it completely if it's not a URL?

+3  A: 

Do you really want to remove the word, or do you just want to prevent it from making your page layout too wide? If the latter is more what you want, consider using CSS to manage the overflow.

For instance:

div { overflow:hidden; }

will hide any content that exceeds the div boundary.

Here's more info on CSS overflow: http://www.w3schools.com/css/pr_pos_overflow.asp

Tom
+5  A: 

Why would you want to remove what the user wrote? Instead, wrap it to a new line - there is a function in PHP to do that, called wordwrap

ehdv
But remember to set 4th param to true so it actually cuts those overlong strings!
Shinhan
wordwrap will break the entire string, not just the long words.
Rob
+2  A: 
// remove words over 30 chars long
$str = preg_replace('/\S{30,}/', '', $str);

edit: updated per Tim P's suggestion, \S matches any non-space char (the same as [^\s])

Also here is a better way incorporating ehdv's suggestion to use wordwrap:

//This will break up the long words with spaces so they don't stretch layouts.
$str = preg_replace('/(\S{30,})/e', "wordwrap('$1', 30, ' ', true)", $str);
Rob
I suggest using /S instead of /w - this will also catch long strings with punctuation, numbers and other special characters.
Tim Pietzcker
$str = preg_replace('/(\S{30,})/e', "wordwrap('$1', 30, ' ', true)", $str);What? You replace actual long strings with literal wordwrap command? Why would you do something like that?
Shinhan
The 'e' modifier evaluates the replacement string.
Rob
A: 

What if it is a really long URL? At any rate why not just match the text to a valid URL, and only accept those? Check out some php-regex info on URLs and see how they work. The Regular Expressions Cookbook has a good chapter on URL matching, as well.

Michael Paulukonis