Forum Moderators: coopster

Message Too Old, No Replies

Stripping Strings of Repeat Spaces or Line Breaks

         

itledi

3:22 pm on Dec 14, 2007 (gmt 0)

10+ Year Member



How can I strip a string of spaces and line breaks if multiple occur in succession?

(spaces resresented by dashes)

This-is-good. => This-is-good.

This-is--not. => This-is-not.

This-is---not. => This-is-not.

This\n
is\n
good.

This\n
\n
is\n
\n
\n
\n
not.

This\n
-\n
-\n
is\n
---\n
not.

I know its something further than:

str_replac(array("--","\n\n"),array("-","\n"),$text);

Any help would greatly be appreciated.

Thanks.

d40sithui

4:11 pm on Dec 14, 2007 (gmt 0)

10+ Year Member



do you mean spaces or dashes?
try preg_replace () since if you have multiple successions, str_replace() will seem to only replace one instance.


<?

$pattern = array("/\s{2,}/", "/\-{2,}/", "/\n{2,}/"); //searches for dashes, spaces, newlines in succession
$replace= array(" ","-","\n");
$text = preg_replace($pattern, $replace, $text);

?>

PHP_Chimp

7:05 pm on Dec 14, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member




$pattern = '%([\s-])+%';
$text = preg_replace($pattern, '$1', $text);

Does the same thing, as above. Just a bit quicker to write :)

You can add anything you want to the character class in the $pattern, as if it is repeated the repeat character will be removed.

[edited by: PHP_Chimp at 7:06 pm (utc) on Dec. 14, 2007]

d40sithui

7:57 pm on Dec 14, 2007 (gmt 0)

10+ Year Member



blast you and your shorter code =P

itledi

1:37 am on Dec 15, 2007 (gmt 0)

10+ Year Member



Thank you, it's a really elegant solutions.

I wasn't trying to match the dashes, I just wanted to show that there might be more than one in a row. I thought that if I had just typed it in, the HTML would just register it as one. So it looks like I can downsize the matching string to just "%(\s)+%".

May I ask what the quotes do? I understand everything else but that part.

Also, I didn't realize you can insert the matching parts back in for the replacement. I've been using the matches in the htaccess files for rewriting urls, but using it in php is a revelation to me.

phranque

2:03 am on Dec 15, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



any language which even pretends to run in a *nix environment will have a regular expression [etext.lib.virginia.edu] engine.