Reputation: 1392
I have a set of strings like this:
Pants [+$50]
Shirts [+$10]
Jeans [+$5]
Jackets [+$100]
How can I remove the ' [xxx]' in these lines and leaving just the item name (without the trailing space)? I was told to define a regular expression, not sure how that works...
Upvotes: 1
Views: 962
Reputation: 11182
Try this one:
The RegEx
(?im)[ \t]*\[[^\]\[]+\][ \t]*$
Code
$result = preg_replace('/^(.+?)[ \t]*\[[^\][]+\][ \t]*$/im', '$1', $subject);
Upvotes: 0
Reputation: 141829
That's actually a bit of a confusing regex, since [
and ]
are special characters:
$str = 'Pants [+$50]';
$str = rtrim(preg_replace('/\[[^\]]*\]/', '', $str));
// 'Pants'
Basically the partern \[[^\]]*\]
means to match a literal [
followed by 0 or more characters that are not ]
followed by a ]
. The second string in preg_replace is what it gets replaced with. In this case the empty string since we want to remove it. Then we use rtrim to trim any trailing whitespace.
Upvotes: 1