如何使用正则表达式从方括号和括号本身之间删除字符串?
让我澄清一下,不是那种情况:[一些文字]而是这个:
Lorem ipsum[:en]Some text[:]
在“str_replace”之后,变量应该只包含:
Lorem Ipsum
有人可以帮助我吗?我要疯了 :)
如何使用正则表达式从方括号和括号本身之间删除字符串?
让我澄清一下,不是那种情况:[一些文字]而是这个:
Lorem ipsum[:en]Some text[:]
在“str_replace”之后,变量应该只包含:
Lorem Ipsum
有人可以帮助我吗?我要疯了 :)
您可以~\[:\w{2}\].*?\[:\]~
用作您的正则表达式。
代码:
$str = "Lorem ipsum [:en]Some text[:] dolor [:en]sit amet[:]";
$new_str = trim(preg_replace(['~\[:\w{2}\].*?\[:\]~', '~\s\s+~'],[' ', ' '], $str));
echo $new_str;
// besides running the regex, this also takes care of multiple whitespaces and whitespaces at the begin and end.
它将转换Lorem ipsum [:en]Some text[:] dolor [:en]sit amet[:]
为Lorem ipsum dolor
它只会匹配和之间[:XX]
的内容[:]
(XX
两个字母数字字符在哪里)。这意味着,Lorem [foobar] ipsum [baz]
将保持原样而不被改变(我猜,这就是你要找的。
例子:
Input: "Lorem ipsum [:en]Some text[:] dolor [:en]sit amet[:]"
Output: "Lorem ipsum dolor"
Input: "Lorem ipsum[:en]Some text[:] dolor[:en]sit amet[:]"
Output: "Lorem ipsum dolor"
Input: "Lorem [foobar] ipsum [baz]"
Output: "Lorem [foobar] ipsum [baz]"
\[ # matches the character [ literally (case sensitive)
: # matches the character : literally (case sensitive)
\w{2} # matches any word character (equal to [a-zA-Z0-9_])
{2} # Quantifier — Matches exactly 2 times
\] # matches the character ] literally (case sensitive)
.*? # matches any character (except for line terminators)
*? # Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)
\[ # matches the character [ literally (case sensitive)
: # matches the character : literally (case sensitive)
\] # matches the character ] literally (case sensitive)
试试这个从字符串中删除 [] 之间。
$str = "Lorem ipsum[:en]Some text[:]";
$new_str = preg_replace('`\[[^\]]*\]`',' ',$str);
echo $new_str;
输出
Lorem ipsum Some text
利用:
\[.+?].+?\[.+?]
解释:
\[ # openning square bracket
.+? # 1 or more any character, not greedy
] # closing square bracket
.+? # 1 or more any character, not greedy
\[ # openning square bracket
.+? # 1 or more any character, not greedy
] # closing square bracket
代码:
$text = 'Lorem ipsum[:en]Some text[:] Lorem ipsum[:en]Some text[:] Lorem ipsum';
echo preg_replace('/\[.+?].+?\[.+?]/', '', $text);
输出:
Lorem ipsum Lorem ipsum Lorem ipsum