PHP preg_replace 删除方括号之间的所有点字符
PHP preg_replace remove all dot character from between square brackets
如何使用 preg_replace 删除字符串中两个方括号之间的所有 .
个字符?
我试图仅在方括号之间进行替换,而不是字符串中的其他点。这应该有效,但不知何故只是给出了一个空白字符串。我该如何为此编写正则表达式?
$str = '[city.name][city.state][city.mayor][city.mayor.name](city.name)';
$str = preg_replace('/\[.*?\]/','',$str);
echo $str;
// output
[cityname][citystate][citymayor][citymayorname](city.name)
您可以使用
'~(?:\G(?!^)|\[)[^][.]*\K\.~' # For [strings]
'~(?:\G(?!^)|<)[^<>.]*\K\.~' # For <strings>
或者,要确保那里有一个关闭的 ]
,添加一个 (?=[^][]*])
前瞻:
'~(?:\G(?!^)|\[)[^][.]*\K\.(?=[^][]*])~' # For [strings]
'~(?:\G(?!^)|<)[^<>.]*\K\.(?=[^<>]*])~' # For <strings>
参见 the regex demo and a regex demo with lookahead。
详情
(?:\G(?!^)|\[)
- [
或上一次成功匹配的结尾
[^][.]*
- 除了 [
、]
和 .
之外的任何 0+ 个字符
\K
- 匹配重置运算符
\.
- 一个点
(?=[^][]*])
- 在当前位置右侧除 ]
和 [
之外的任何 0+ 个字符之后需要 ]
的正向前瞻。
$str = '[city.name][city.state][city.mayor][city.mayor.name](city.name)';
echo preg_replace('~(?:\G(?!^)|\[)[^][.]*\K\.~', '', $str);
您可以像
那样使用 \G
(?:\G(?!\A)|\[)
[^\].]*\K\.
参见 a demo on regex101.com(注意详细模式)。
分解后,这表示:
(?:
\G(?!\A) # match after the previous match (not the start)
| # or
\[ # [
)
[^\].]* # neither dot nor ]
\K # make the engine forget what's been matched before
\. # match a dot
使用回调
$str = preg_replace_callback('/\[[^]]*\]/', function($m){
return str_replace(".", "", $m[0]);
}, $str);
如何使用 preg_replace 删除字符串中两个方括号之间的所有 .
个字符?
我试图仅在方括号之间进行替换,而不是字符串中的其他点。这应该有效,但不知何故只是给出了一个空白字符串。我该如何为此编写正则表达式?
$str = '[city.name][city.state][city.mayor][city.mayor.name](city.name)';
$str = preg_replace('/\[.*?\]/','',$str);
echo $str;
// output
[cityname][citystate][citymayor][citymayorname](city.name)
您可以使用
'~(?:\G(?!^)|\[)[^][.]*\K\.~' # For [strings]
'~(?:\G(?!^)|<)[^<>.]*\K\.~' # For <strings>
或者,要确保那里有一个关闭的 ]
,添加一个 (?=[^][]*])
前瞻:
'~(?:\G(?!^)|\[)[^][.]*\K\.(?=[^][]*])~' # For [strings]
'~(?:\G(?!^)|<)[^<>.]*\K\.(?=[^<>]*])~' # For <strings>
参见 the regex demo and a regex demo with lookahead。
详情
(?:\G(?!^)|\[)
-[
或上一次成功匹配的结尾[^][.]*
- 除了[
、]
和.
之外的任何 0+ 个字符
\K
- 匹配重置运算符\.
- 一个点(?=[^][]*])
- 在当前位置右侧除]
和[
之外的任何 0+ 个字符之后需要]
的正向前瞻。
$str = '[city.name][city.state][city.mayor][city.mayor.name](city.name)';
echo preg_replace('~(?:\G(?!^)|\[)[^][.]*\K\.~', '', $str);
您可以像
那样使用\G
(?:\G(?!\A)|\[)
[^\].]*\K\.
参见 a demo on regex101.com(注意详细模式)。
分解后,这表示:
(?:
\G(?!\A) # match after the previous match (not the start)
| # or
\[ # [
)
[^\].]* # neither dot nor ]
\K # make the engine forget what's been matched before
\. # match a dot
使用回调
$str = preg_replace_callback('/\[[^]]*\]/', function($m){
return str_replace(".", "", $m[0]);
}, $str);