Regex将空格和方括号替换为下划线


Regex to replace spaces and brackets with underscore

我有一些字符串,格式如下:

this is a string
This is a string
This is a (string)
This is a  string

我想要一个正则表达式将其转换为以下内容:

this_is_a_string

没有领先的

我使用preg_replace得到了以下内容,这几乎让我一路过关斩将:

preg_replace('/[^A-Za-z]+/', '_', $string)

但是,它将最后一个)转换为下划线,这对于我的使用是不可接受的。我可以在一个单独的函数中很容易地将其删除,但我想知道是否可以使用一个正则表达式?

$result = preg_replace('~[^A-Z]+([A-Z]+)(?:[^A-Z]+$)?~i', '_$1', $string);
$result = preg_replace('~([^a-zA-Z'n'r()]+)~', '_', $string);

在这里试试

请确保字符串中没有尾随空格或前导空格,否则它也会被替换。。。使用trim($string)将其删除

正则表达式是一个很好的工具,但也有一些不太适合它们的地方。转换字符大小写是正则表达式无法单独完成的一件事。您可以使用preg_replace_callback函数将匹配的文本转换为小写,但这实际上是非常直接的,只需稍微更改一下逻辑即可实现。

也许是这样的:

$string = 'This is a (string)';
preg_match_all("/[a-zA-Z]+/", $string, $matches);
$string = strtolower(implode('_', $matches[0])); // this_is_a_string