1

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...

0

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this one:

The RegEx

(?im)[ \t]*\[[^\]\[]+\][ \t]*$

Code

$result = preg_replace('/^(.+?)[ \t]*\[[^\][]+\][ \t]*$/im', '$1', $subject);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.