开发者

How to remove a long word from a string

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 U开发者_运维问答RL?


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


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


// 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);


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.


@Rob care in using REGEX. Performance lookout.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜