如何编写一个regex,它只将由任何字符组成的标准字符串转换为仅以_
、-
、$
或非重音字母开头,而字符串的其余部分只能包含这些字符或非重音字符?
我可以用preg_replace("/[^a-zA-Z]/", "", $value)
获得所有非数字,但这不是我需要的。
我想做的是获取一个字符串,它的首字母可能是4_The quick brown fox jumps o8ver the lazy dog and the slow white dog fox jumps over the unlazy fox.
并将其转换为_Thequickbrownfoxjumpsoverthelazydogandtheslowwhitedogfoxjumpsovertheunlazyfox
以下模式将删除一个或多个不在连字符、下划线、美元符号或字母白名单上的字符。
当在整个字符串中使用相同的清理时,没有必要指定字符串的开头。
代码:(演示(
$string = '4_The quick brown fox jumps o8ver the lazy dog and the slow white dog fox jumps over the unlazy fox.';
var_export(
preg_replace(
'~[^-_$a-z]+~i',
'',
$string
)
);
输出:
'_Thequickbrownfoxjumpsoverthelazydogandtheslowwhitedogfoxjumpsovertheunlazyfox'