views:

87

answers:

6

Hi,

how do I strip off all white space and  ?

I have this as a input in a wrapper I create,

[b]       bold       [/b]

so before turning the text to bold, i want to strip off all white spaces and &nbsp, and turn it into [b]bold[/b],

$this->content = preg_replace("/\[(.*?)\]\s\s+(.*?)\s\s+\[\/(.*?)\]/", 
                "[$1]$2[/$3]", 
                $this->content);

but it does not work! can you help please?

Many thanks, Lau

+2  A: 

There is no need for a regex based solution. You can simply use str_replace as:

$input = "[b]       bold       [/b]";
$input = str_replace(array(' ',' '),'',$input);
echo $input; // prints [b]bold[/b]
codaddict
This will remove the whitespace outside the `[b]`, too. But I don't know whether that's expected behavior or not.
nikic
Looking at his sample input/output looks like thats what he wants.
codaddict
Except that the sample doesn't show text outside of the tags.
poke
A: 

You can just replace the spaces with empty strings, e.g.

preg_replace("/(?:\s| )+/", "", $this->content, -1)

The -1 causes the replace to hit every instance of the match.

Matt Kane
+1  A: 
$this->content = preg_replace(
    '~\[(.*?)](?:\s| )*(.*?)(?:\s| )*\[/\\1]/', 
    '[$1]$2[/$1]', 
    $this->content
);
nikic
That wouldn't work either. The original question didn't show the ` ` characters that OP wants to be removed. Also your solution will not work at all, since the square brackets are not escaped, and all your grouping doesn't help either.
poke
@poke: I don't get what you want to say. The closing square bracket `]` doesn't need to be escaped. All I did was take the OPs regex, remove unnecessary parts and add recognition of ` `.
nikic
@nikic: Huh? Did you change your answer in between?
poke
@poke: I think you are referring to another answer. I didn't change this one.
nikic
@nikic: o.O Yeah I think so, my bad then.. *confused* - Could you slightly change your answer (add a space or something) so I can remove the -1 again?
poke
@poke: Sure *;)*
nikic
A: 

To give you a complete solution with regular expressions as well:

$this->content = preg_replace( '/\[([a-z]+)\](?: |\s)*(.*?)(?: |\s)*\[\/([a-z]+)\]/', '[$1]$2[/$3]', $this->content );

But in this case you should rather combine the whitespace removal and bbcode transformation to make sure that the tags are correctly:

$this->content = preg_replace( '/\[b\](?:&nbsp;|\s)*(.*?)(?:&nbsp;|\s)*\[\/b]/', '<b>$2</b>', $this->content );
poke
thank you so much! this is what I want! thanks! :-))))
lauthiamkok
A: 

Another method that would work is:

$this->content = trim(str_replace('&nbsp;','',$this->content));

PHP Manual links:

trim() http://us.php.net/trim

*note: This is assuming $this->content contains only the string posted by OP

David
A: 

I found another solution

$this->content = preg_replace("/\[(.*?)\]\s*(.*?)\s*\[\/(.*?)\]/", "[$1]$2[/$3]", html_entity_decode($this->content));

thank you so much guys!

lauthiamkok