HTML Super Trim Functions
Remove non breaking spaces and other white space either side of strings
// wrapper function to do trim both sides
function HTMLTrim($text){
// call both functions at once
return HTMLLeftTrim(HTMLRightTrim($text));
}
// removes spaces and at the beginning of strings
function HTMLLeftTrim($text){
// remove space to the left of the text
return preg_replace("@^( | |\s)+(\S+)@","$2",$text);
}
// removes spaces and at the beginning of strings
function HTMLRightTrim($text){
// remove space to the right of the text
return preg_replace("@(\S+)( | |\s)+$@","$1",$text);
}$str = " hello there     ";
echo "before trim its '" . $str . "'";
echo "<br><br>now its '" . HTMLTrim($str) . "'";
before trim its ' hello there '
now its 'hello there'
I find it very useful when I am scraping content from the web and need to handle the removal of a mixture of standard spaces and HTML spaces.
Labels: HTML Encode, PHP, RegEx, regular expression, TRIM



0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
Links to this post:
Create a Link
<< Home