I want this out come
Input =|= Output
=============================开发者_如何学JAVA================
[b] [/b] =|= [b][/b]
[b] [/b] =|= [b][/b]
[b]Hii[/b] =|= [b]Hii[/b]
[b]Hello There[/b] =|= [b]Hello There[/b]
I think the only way to solve this problem is regex which i dont know to write, so looking for help
input = input.replace(/\[b\]\s+\[\/b\]/ig, '[b][/b]');
Demo →
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);
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
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! :)
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.
It seems like you are trying to get rid of the spaces before and after your string only.
In php there is a native function that does just that
trim()
Read here
Here is an example:
$string = ' Hello World! ';
$trimmed = trim($string);
echo $trimmed;
// will print 'Hello World'
精彩评论