A little late to answer but hopefully might help someone else. The most important while extracting content from html is to use utf8_decode() in php (Community warning: "This function is DEPRECATED as of PHP 8.2.0. Relying on this function is highly discouraged" - from PHP manual). Then all other string operations become a breeze. Even foreign characters can be replaced by directly copy pasting characters from browser into the php code. The following function replaces
with a space. Then all extra white spaces are replaced with a single white space using preg_replace()
. Leading and trailing white spaces are removed in the end.
function clean($str)
{
$str = utf8_decode($str);
$str = str_replace(" ", " ", $str);
$str = preg_replace('/\s+/', ' ',$str);
$str = trim($str);
return $str;
}
$html = "1 $nbsp; 2 3 4";
$output = clean($html);
echo $output;
1 2 3 4