将两个字符串分成相等的部分并在其间添加一个单词

时间:2014-11-27 18:41:10

标签: php string

我想将字符串中的单词除以相等的部分,然后在中间添加一些内容。

$string = "hello i am superman and also batman";
$insert = "word";

所以我希望结果是

$result= "hello i am superman word and also batman";

我尝试了什么......但是下面的代码很脏......请问任何简单的方法吗?

$word = "word";
$arr = explode(" ",$string);
$count = round(sizeof($arr)/2);
$i=0;
foreach($arr as $ok)
{

if($i == $count)
{
$new.=$ok." ".$word;
}
else
{
$new.= $ok." ";
}
$i++;
}

echo trim($new);

2 个答案:

答案 0 :(得分:1)

您可以使用array_splice。以下示例:

$string = "hello i am superman and also batman";
$insert = "word";

$string_array = explode(' ',$string);

array_splice( $string_array, round(count($string_array)/2), 0, array($insert) );

echo implode(' ', $string_array);

或将其用作功能:

function insertString($string, $insert){

    $string_array = explode(' ',$string);

    array_splice( $string_array, round(count($string_array)/2), 0, array($insert) );

    return implode(' ', $string_array);

}

echo insertString('hello i am superman and also batman','word');

输出将是:

hello i am superman word and also batman

答案 1 :(得分:1)

这实际上非常简单,只要您能接受将字符串拆分为“相等部分”的一点点宽容。在这种情况下,我正在考虑字符数而不是字数。使用strpos确定字符串“中间”点后第一个空格的位置:

$insertPoint = strpos($string, ' ', strlen($string) / 2);

然后在那里注入这个词! (使用this SO answer to achieve this

$new = substr_replace($string, ' '.$insert, $insertPoint, 0);