-2

如何使用正则表达式从方括号和括号本身之间删除字符串?

让我澄清一下,不是那种情况:[一些文字]而是这个:

Lorem ipsum[:en]Some text[:]

在“str_replace”之后,变量应该只包含:

Lorem Ipsum

有人可以帮助我吗?我要疯了 :)

4

3 回答 3

0

您可以~\[:\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]"

在行动中看到它!

解释:
\[:\w{2}\].*?\[:\]

\[    # 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)
于 2019-10-03T12:33:33.320 回答
0

试试这个从字符串中删除 [] 之间。

 $str = "Lorem ipsum[:en]Some text[:]";
   $new_str = preg_replace('`\[[^\]]*\]`',' ',$str);

   echo $new_str;

输出

Lorem ipsum Some text

演示

于 2019-10-03T10:21:35.697 回答
0

利用:

\[.+?].+?\[.+?]

解释:

\[      # 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
于 2019-10-03T11:59:49.223 回答