Reputation: 23959
I know how to remove specific character within a string but not sure about the following:
e.g. string: Code [7845] [5589] [554] [4]
I need to remove all instances of [
and ]
and everything in between them, then trim whitespace off so I end up with simply: Code
Is this possible?
Upvotes: 2
Views: 3523
Reputation: 26930
This would do it :)
$result = preg_replace('/\[.*?\]|\s*/', '', $subject);
Explanation:
"
\[ # Match the character “[” literally
. # Match any single character that is not a line break character
* # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\] # Match the character “]” literally
"
As @Felix points out this is a fairly easy expression. You should take a look here and try to familiarize yourself with the various techniques you can use.
Upvotes: 5
Reputation: 77995
You need to provide more details concerning your requirements.
Assuming:
$s = 'Code [7845] [5589] [554] [4]';
If the string always starts with what you're after and the rest can always be discarded, then this would probably be the most efficient:
$s = trim(substr($s, 0, strpos($s, '[')));
If you want to keep the original string and only remove groups of digits, then:
$s = trim(preg_replace('/\[\d+\]/', '', $s));
Upvotes: 1
Reputation: 5692
try the following:
$str = trim(preg_replace('/\[\d+\]/', '', 'your_string_here'));
The first argument of the function is a regex. \d
that you see matches a number, and the +
following it says that you should match at least 1 number. Check here for more information on preg_replace. Check here for more information on Regex.
Upvotes: 1