preg_replace_callback PHP function:
http://www.php.net/manual/en/function.preg-replace-callback.php
The regular expression:
(?s-imx:<.*?>|[^\s<>]{30,})
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?s-imx: group, but do not capture (with . matching
\n) (case-sensitive) (with ^ and $ matching
normally) (matching whitespace and #
normally):
----------------------------------------------------------------------
< '<'
----------------------------------------------------------------------
.*? any character (0 or more times (matching
the least amount possible))
----------------------------------------------------------------------
> '>'
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
[^\s<>]{30,} any character except: whitespace (\n, \r,
\t, \f, and " "), '<', '>' (at least 30
times (matching the most amount possible))
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
After the initial matches are created they are passed to the function one by one, the function tests if the match is a <> block to be ignored, and if not it will be matched in 10 character long segments, between each segment a space will be inserted ("\0 " means the match plus a space character). Instead of a space character you might consider a replacement such as "\0<wbr>" to keep from breaking the text yet support word wrapping at 10 character intervals.
Like most solutions, there are other options for accomplishing the same task, here's a similar option that eliminates the extra preg_match operation by using matching capture groups in the initial preg_replace_callback function:
<?php
$string='Then after it finds a 30+ word it then checks if it is a URL so it dosnt mess with the links <a href="http://dont-mess-with-url-dont-mess-with-url-dont-mess-with-url-">mess-with-name-of-link-if-you-want-mess-with-name-of-link-if-you-want</a>';
function replfunc($match){
if ($match[1]) {
return $match[0];
} else {
return preg_replace('/\S{10}/','\0<wbr>',$match[0]);
}
}
$string=preg_replace_callback('/(<.*?>)|[^\s<>]{30,}/s','replfunc',$string);
echo $string;
?>