Reputation: 117
I'm outputting a huge string which is created by a WYSIWYG editor. The following is an example of an output that the editor makes. I'm trying to prevent all the spaces created by the  
's from the beginning and end (inside each tag), so that the tags tightly wrap the content. Rtrim and Ltrim don't work because they trim the whole string, not the tags inside it.
Here is an example of a string.
<div> Small amount of text, should be alot.</div>
<div>Small amount of text, should be alot. </div>
This will output something along the lines of the following (the div has been left in to show the extent of the spaces, but would be hidden on output.)
<div> Small amount of text, should be alot.</div>
<div>Small amount of text, should be alot. </div>
I would prefer this out output..
<div>Small amount of text, should be alot.</div>
<div>Small amount of text, should be alot.</div>
How can this be achieved?
Upvotes: 0
Views: 3187
Reputation: 1993
I assume that your final goal is:
with " "you can achieve that by:
//1 replace hard spaces with spaces
$text = str_replace(' ', ' ', $text);
//2 squeeze spaces
$text = preg_replace('/\s+/', ' ', $text);
//replace "> " & " <" with ">" & "<" respectively
$result = str_replace(array('> ', ' <'), array('>', '<'), $text);
Upvotes: 1
Reputation: 32232
Replace repetitions of spaces and/or
with a single  
:
preg_replace('/(?: | ){2,}/', ' ', $string);
If you want to convert all
to spaces, and then collapse the spaces then:
preg_replace('/ {2,}/', ' ', str_replace(' ', ' ', $string));
Note that this is not going to remove single spaces from after the opening tag, or before the closing tag. For something like that you're getting into some pretty nasty territory with regular expressions and you'll want to parse the document using DOM or XML instead.
However, leading and trailing whitespace is generally insignificant in HTML, so this should get you where you're going.
Upvotes: 1
Reputation: 2759
Why not trying replacing the string?
$newStr = str_replace(" ", "", $oldStr);
Upvotes: 0