PHP删除[:en] [:]

时间:2019-10-03 10:11:56

标签: php regex wordpress qtranslate-x

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

让我澄清一下,不是这种情况:[某些文本]而是这种情况:

Lorem ipsum[:en]Some text[:]

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

Lorem Ipsum

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

3 个答案:

答案 0 :(得分:0)

尝试此操作从字符串中的[]之间删除。

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

   echo $new_str;

输出

Lorem ipsum Some text

DEMO

答案 1 :(得分: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

答案 2 :(得分: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]"

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)