您可以使用~\[:\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] 将保持原样而不被更改(我猜,这就是您要寻找的。p>
示例:
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]"
See it in action!
说明:
\[:\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)