[英]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)? 如何删除这些行中的“ [xxx]”并仅保留商品名称(没有尾随空格)? 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 ]
. 基本上,partern
\\[[^\\]]*\\]
装置以匹配字面[
后跟0或多个字符不那]
后跟一个]
。 The second string in preg_replace is what it gets replaced with. preg_replace中的第二个字符串就是它所替换的字符串。 In this case the empty string since we want to remove it.
在这种情况下,因为我们要删除它,所以它是空字符串。 Then we use rtrim to trim any trailing whitespace.
然后,我们使用rtrim修剪任何尾随空白。
Try this one: 试试这个:
The RegEx 正则表达式
(?im)[ \t]*\[[^\]\[]+\][ \t]*$
Code 码
$result = preg_replace('/^(.+?)[ \t]*\[[^\][]+\][ \t]*$/im', '$1', $subject);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.