Skip to content Skip to sidebar Skip to footer

Remove Space/spaces Between Two Words

I want this out come Input =|= Output ============================================= [b] [/b] =|= [b][/b] [b] [/b] =|= [b][/b] [b]Hii[/b]

Solution 1:

input = input.replace(/\[b\]\s+\[\/b\]/ig, '[b][/b]');

Demo →

Solution 2:

For JavaScript:

input = input.replace(/\[b\](?: |\s)+?\[\/b\]/gi, '[b][/b]');

For PHP:

$input = preg_replace('/\[b\](?: |\s)+?\[\/b\]/i', '[b][/b]', $input);

The above includes   since the example formerly showed that. If there is no need, just use:

For JavaScript:

input = input.replace(/\[b\]\s+?\[\/b\]/gi, '[b][/b]');

For PHP:

$input = preg_replace('/\[b\]\s+?\[\/b\]/i', '[b][/b]', $input);

But these will only catch empty whitespace not trailing.

To catch trailing...

For JavaScript:

input = input.replace(/\[b\](.+?)\[\/b\]/gi, function (n0, n1) {
    return'[b]' + n1.replace(/^\s+|\s+$/g, '') + '[/b]';
});

For PHP:

$input= preg_replace_callback('/\[b\](.+?)\[\/b\]/i', 
    create_function(
        '$m',
        'return"[b]".trim($m[1])."[/b]";'
    ), 
    $input);

Solution 3:

input.replace(/\s+/g,'') will take out all spaces (which it sounds like what you are trying to do) even though your last example confuses me

Solution 4:

Um.. I think I get what you mean when I read your question, but your example confused me a lot. You have both PHP & Javascript written... IF you wanna do this is PHP use preg_replace() $str = 'the value you want to parse';

$new_value = preg_replace('/\s\s+/', '', $str);

Hope this helps! :)

Solution 5:

This should do it:

preg_replace ("/\s+/", "\s", $subject);
preg_replace ("/\]\s+\[/", "\]\[", $subject);

It could be done with a single regex, but it's much easier to understand in 2 passes.

Post a Comment for "Remove Space/spaces Between Two Words"