spudly Posted July 14, 2007 Share Posted July 14, 2007 PHP version 4.4.4 I'm trying to get preg_replace to work but I can't figure out why it isn't. Here's my code: $vars["html"] = preg_replace("/\s+/", " ", $vars["html"]); echo $vars["html"]; Previous this this exerpt, $vars["html"] is a string filled with html code. I'm simply trying to replace all whitespace characters (tabs, spaces, newlines, etc...) with one space. The problem is that nothing happens. preg_replace is returning the original string and does not strip the whitespace. help? Quote Link to comment Share on other sites More sharing options...
Caesar Posted July 14, 2007 Share Posted July 14, 2007 Try... <?php $string = htmlentities($vars['html']); $newstr = preg_replace('/[\s]+?[\n]?[\r]/i', ' ', $string); ?> Quote Link to comment Share on other sites More sharing options...
Wuhtzu Posted July 14, 2007 Share Posted July 14, 2007 The code you have posted works for me... remember that most of the changes done by this replacement will only be visible when viewing the page's source code. When I tried your code the string I tested with contained tabs but they were displayed as spaces in firefox, only the source code showed the difference... If you can't get it to work try this: preg_replace("/[\s]+/", " ", $string) Quote Link to comment Share on other sites More sharing options...
Caesar Posted July 14, 2007 Share Posted July 14, 2007 The regex pattern you are using only looks for spaces. You mentioned you want to also remove lines breaks etc....I tested the code I posted above...and it seemed to work fine. Quote Link to comment Share on other sites More sharing options...
Wuhtzu Posted July 14, 2007 Share Posted July 14, 2007 The regex pattern you are using only looks for spaces. You mentioned you want to also remove lines breaks etc....I tested the code I posted above...and it seemed to work fine. Not true The \s means whitespace including spaces, tabs and newlines/linebreakes: Trimming Whitespace You can easily trim unnecessary whitespace from the start and the end of a string or the lines in a text file by doing a regex search-and-replace. Search for ^[ \t]+ Analyze this regular expression with RegexBuddy and replace with nothing to delete leading whitespace (spaces and tabs). Search for [ \t]+$ Analyze this regular expression with RegexBuddy to trim trailing whitespace. Do both by combining the regular expressions into ^[ \t]+|[ \t]+$ Analyze this regular expression with RegexBuddy. Instead of [ \t] which matches a space or a tab, you can expand the character class into [ \t\r\n] if you also want to strip line breaks. Or you can use the shorthand \s instead. When I tested the \s 5min ago it matched exactly what the above quote states Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.