【问题标题】:How do I concatenate PHP strings without making PHP copy values from one location to another in memory?如何连接 PHP 字符串而不使 PHP 将值从内存中的一个位置复制到另一个位置?
【发布时间】:2016-03-27 03:28:48
【问题描述】:

我做了一个函数,它接受任意数量的单词作为参数,并将每个单词的第一个字母大写。

我查看了这个网站:http://www.carlconrad.net/en/2014/03/17/improving-php-performance/,它说:

避免循环中的字符串连接。当放置在循环中时,字符串连接会导致创建大量临时对象并不必要地使用垃圾收集器。两者都会消耗内存并且会显着减慢脚本的执行速度。

我试图弄清楚如何修改下面的代码以使其运行得更快。是否有另一种方法可以在不依赖原始值的情况下在 PHP 中连接字符串?

我知道在原始 C 语言中,我可以使用字符串的地址指针加上定义范围内的偏移量来添加数据,而不必担心原始字符串被复制到其他地方,而源声称 PHP 在连接期间所做的事情。

理想情况下,我希望我的字符串连接能够像这段 C 代码那样工作(假设我们在 main() 函数中):

char string[1000];
memcpy(string,'ABCD',4); //place ABCD at start
memcpy(string+4,'EFGH',4); //add EFGH to the string (no previous string copying required)

只是简单的连接,不操作字符串的前一个值。

这是我需要改进建议的 php 代码:

function capitalize($words){
    $words=$words.' ';
    $returnedwords='';
    $eachword=explode(' ',$words);$numberofwords=count($eachword);
    if ($numberofwords >=1){
        $wordkey=array_keys($eachword);
        for($thiswordno=0;$thiswordno<$numberofwords;$thiswordno++){
            $word=$eachword[$wordkey[$thiswordno]];
            $returnedwords.=' '.strtoupper(substr($word,0,1)).strtolower(substr($word,1));
        }
        return substr($returnedwords,1);
    }
}

有什么想法可以遵循网站的建议来避免像我在循环中那样在循环中连接字符串吗?

【问题讨论】:

  • 为什么不用php的ucwords函数?
  • 我什至不知道有这样的功能。
  • 查看我的答案.. 我放置了一个链接供您参考,这样您就可以了解 php 中的所有字符串函数

标签: php string memory concatenation copying


【解决方案1】:

在php中它具有将字符串的第一个单词作为大写的功能。

示例1:字符串的ucword:

$str = 'this is test value of data';
echo ucwords('this is test value of data');

输出:这是数据的测试值

示例 2:从包含多个单词的数组创建 ucword 字符串:

$str = array(
    'this',
    'is',
    'test',
    'VALUE',
    'of',
    'Data'
);

$str = array_map('ucwords', array_map('strtolower', $str));

echo implode(' ', $str);

输出:这是数据的测试值

更多详情请看:PHP String Functions

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-01
    • 2014-11-25
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    相关资源
    最近更新 更多