【问题标题】:Most efficient way of certain string manipulation in PHP?PHP中某些字符串操作的最有效方法?
【发布时间】:2012-01-25 23:56:41
【问题描述】:

我有需要像这样转换的字符串,

'hello world' = 'helloWorld'

反过来也一样,

'helloWorld' = 'hello world'

到目前为止,我对这两种转换的所有信息都是第一次,

$str = 'hello world';
$str = lcfirst(str_replace(' ', '', ucwords($str))); // helloWorld

第二个,

$str = 'helloWorld';
$str = preg_split('/(?=[A-Z])/', $str);
$str = strtolower(implode(' ', $str)); // hello world

这不能更容易或更有效地实现吗?

【问题讨论】:

  • 这有什么低效的?我觉得很好
  • 最有效的方法是最易读的,没有失败。不要为了每个请求 0.04 毫秒而使您的代码令人眼花缭乱。

标签: php string


【解决方案1】:

你的骆驼代码已经很好了。对于第二个,你可以放弃分裂和内爆:

$str = 'helloWorld';
$str = strtolower(preg_replace('/(?<=\\w)([A-Z])/', ' \\1', $str));
echo $str;
// output: hello world

【讨论】:

  • 谢谢 试试这个,我之前用preg_replace 试过,但不能正确。
  • 这很棒!你能告诉我' \\1'那个位是什么意思吗?或者是一个链接,以便我找出来?
  • 这是一个back reference。它告诉正则表达式获取它在原始字符串中找到的文本并将其“粘贴”回此处。
  • 谢谢,这比我用的好。
猜你喜欢
  • 2019-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-14
  • 1970-01-01
  • 1970-01-01
  • 2010-09-06
相关资源
最近更新 更多