php 删除多个空格

发布于 2024-10-30 06:58:47 字数 204 浏览 1 评论 0原文

我遇到了一些麻烦,我想知道是否有人知道 preg_replace 正则表达式,它可以删除除字符串中遇到的第一个空格之外的所有空格。

|示例|

我有以下字符串:“My First Last Name”


我想要实现的目标是:“My FirstLastName”

抱歉,但我对正则表达式非常不好:( 所以非常感谢任何帮助。

I've been having some trouble, i was wondering if anyone knows of a preg_replace regex which can remove all spaces except the first one it encounters from a string.

|EXAMPLE|

I have the following string: "My First Last Name"


What i would like to achieve is something like: "My FirstLastName"

Sorry but i'm pretty bad with regex :( so any help is appreciated.

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

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

发布评论

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

评论(2

人海汹涌 2024-11-06 06:58:47

实际上,您并不需要正则表达式来执行此操作,只需将字符串拆分为空格,然后再次将其连接起来会更快。

$name = "My First Last Name"
$pieces = explode(" ", $name, 2); // split into 2 strings
// $pieces[0] is before the first space, and $pieces[1] is after it
// so we can make the new string joining them together 
// and just removing all spaces from $pieces[1]
$newName = $pieces[0] . " " . str_replace(" ", "", $pieces[1]);

You don't actually need regex to do that, it's quicker to just split the string on spaces and then join it up again.

$name = "My First Last Name"
$pieces = explode(" ", $name, 2); // split into 2 strings
// $pieces[0] is before the first space, and $pieces[1] is after it
// so we can make the new string joining them together 
// and just removing all spaces from $pieces[1]
$newName = $pieces[0] . " " . str_replace(" ", "", $pieces[1]);
逆流 2024-11-06 06:58:47

不需要使用正则表达式,只需找到第一个空格,保留该字符串的那一部分,然后替换其余部分:

$first_space = strpos($string, ' ');
$string = substr($string, 0, $first_space+1) 
   . str_replace(' ', '', substr($string, $first_space+1));

No need to use regex, just find the first space, keep that piece of the string, and replace the rest:

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