Jump to content

preg_replace not working


spudly

Recommended Posts

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?

Link to comment
Share on other sites

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)

Link to comment
Share on other sites

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 :)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.