简体   繁体   中英

PHP String Pattern Replace

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

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.

Try this one:

The RegEx

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

Code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM