【问题标题】:Sanitize string to start only with _, -, $ or letter & the rest can only have those characters清理字符串以仅以 _、-、$ 或字母开头,其余的只能包含这些字符
【发布时间】:2020-11-17 03:53:41
【问题描述】:

如何编写一个正则表达式,它只将由任何字符组成的标准字符串转换为只以_-$ 或非重音字母开头,而字符串的其余部分只能有那些字符或非重音字母?

我可以使用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

【问题讨论】:

  • ok @anubhava 我有一个我所做的样本
  • 问题不清楚。示例会很有帮助。
  • @rgbflawed 我有一个例子
  • 喜欢这个? (?:^[^_$a-zA-Z-]+|[^$\w-]+)regex101.com/r/jQCqch/1

标签: php regex string replace


【解决方案1】:

以下模式将删除一个或多个不在连字符、下划线、美元符号或字母白名单上的字符。

如果在整个字符串中使用相同的清理,则不必指定字符串的开头。

代码:(Demo)

$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'

【讨论】:

    猜你喜欢
    • 2021-12-02
    • 2014-05-21
    • 2019-11-11
    • 2023-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    相关资源
    最近更新 更多