Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/238.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP转换字符串_Php_String - Fatal编程技术网

PHP转换字符串

PHP转换字符串,php,string,Php,String,我有一个字符串:$str='hello all world'。我想将此字符串转换为你好,大家好,世界。所以,基本上就在字符串的最后一个单词之前,它应该有&,其他的应该通过,连接起来 我尝试了以下方法: <?php $str = 'hello-all-the-world'; $arr = explode('-', $str); // lost from here 您可以很容易地做到这一点,如果您在使用array\u pop分割后切断最后一个数组元素,那么您可以使用,内爆剩余的元素,并

我有一个字符串:
$str='hello all world'
。我想将此字符串转换为
你好,大家好,世界
。所以,基本上就在字符串的最后一个单词之前,它应该有
&
,其他的应该通过
连接起来

我尝试了以下方法:

<?php

$str = 'hello-all-the-world';

$arr = explode('-', $str);

// lost from here

您可以很容易地做到这一点,如果您在使用array\u pop分割后切断最后一个数组元素,那么您可以使用
内爆剩余的元素,并在
&
之后再次添加最后一个元素:

$str = 'hello-all-the-world';

$arr = explode('-', $str);
$last = array_pop($arr); // pop last item from array

echo implode(', ', $arr) . ' &amp; ' . $last;

// result: hello, all, the & world
您可以尝试:

<?php

$str = 'hello-all-the-world';

$arr = explode('-', $str);
$last = array_pop($arr);
$ans = implode(', ', $arr) . ' & ' . $last;