用下划线替换非字母数字字符

发布于 2024-07-17 04:41:37 字数 403 浏览 7 评论 0原文

这就是我当前正在使用的:

$replace = array(" ", ".", ",", "'", "@");
$newString = str_replace($replace, "_", $join);

$join = "the original string i'm parsing through";

我想删除除 azAZ0-9 之外的所有内容。 我正在寻找上述函数的反向函数。 编写它的伪代码方式是

如果$join中的字符不等于az,AZ,0-9 然后将 $join 中的字符更改为 "_"

This is what I'm currently using:

$replace = array(" ", ".", ",", "'", "@");
$newString = str_replace($replace, "_", $join);

$join = "the original string i'm parsing through";

I want to remove everything which isn't a-z, A-Z, or 0-9. I'm looking for a reverse function of the above. A pseudocode way to write it would be

If characters in $join are not equal to a-z,A-Z,0-9
then change characters in $join to "_"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

蔚蓝源自深海 2024-07-24 04:41:37
$newString = preg_replace('/[^a-z0-9]/i', '_', $join);

这应该可以解决问题。

$newString = preg_replace('/[^a-z0-9]/i', '_', $join);

This should do the trick.

德意的啸 2024-07-24 04:41:37

除 az、AZ、0-9 之外的任何内容的正则表达式为

preg_replace('/[^a-zA-Z0-9]/', "_", $join);

: ">否定字符类

The regular expression for anything which isn't a-z, A-Z, 0-9 is:

preg_replace('/[^a-zA-Z0-9]/', "_", $join);

This is known as a Negated Character Class

多像笑话 2024-07-24 04:41:37

最简单的方法是这样的:

preg_replace('/\W/', '_', $join);

\W 是非单词字符组。 单词字符包括 az、AZ、0-9 和 _。 \W 匹配之前未提及的所有内容*。

编辑: preg 使用 Perl 的正则表达式,记录在 perlman perlre 文档中。

*编辑 2:这假定为 C 或英语语言环境之一。 其他语言环境可能在单词字符类中具有重音字母。 Unicode 区域设置仅将代码点 128 以下的字符视为字符。

The easiest way is this:

preg_replace('/\W/', '_', $join);

\W is the non-word character group. A word character is a-z, A-Z, 0-9, and _. \W matches everything not previously mentioned*.

Edit: preg uses Perl's regular expressions, documented in the perlman perlre document.

*Edit 2: This assumes a C or one of the English locales. Other locales may have accented letters in the word character class. The Unicode locales will only consider characters below code point 128 to be characters.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文