php添加单词而不重复字符串中的随机位置

时间:2013-09-07 09:38:49

标签: php arrays string random repeat

我有一个像这样的字符串和关键字数组。

$string = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa";

$keywordsArr = array('FOOO' => 3,'BAR' => 2);

所以我需要根据关键字数组将这些关键字放入字符串中,如下所示。并且不重复这些关键词。

$string = "Lorem ipsum dolor FOOO sit amet, consectetuer adipiscing BAR elit. Aenean commodo FOOO ligula eget dolor. Aenean FOOO massa BAR";
// 3 times FOOO and 2 times BAR

不要这样重复。

$string = "Lorem ipsum dolor FOOO FOOO FOOO sit amet, consectetuer adipiscing BAR BAR elit. Aenean commodo ligula eget dolor. Aenean massa";

任何人都可以帮助我吗?真的很感激。 感谢

2 个答案:

答案 0 :(得分:1)

    $string = "Lorem ipsum FOO dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis";
$keywordsArr = array('FOO' => 4, 'BAR' => 2);
$sResult = addWordToString($string, $keywordsArr);


function addWordToString($string, $keywordsArr) {

    $dStringLength = strlen($string);
    //converting the string into an array depending on the spaces
    $aStringContent = explode(' ', $string);
    $dLength = count($aStringContent);
    //loop the keyword array
    foreach ($keywordsArr as $key => $value) {
        //check if the word occured the number times of value
        $sRegularExperssion = "/$key/";
        $dNumberOfMatches = preg_match($sRegularExperssion, $string);
        if ($dNumberOfMatches >= $value) {
            echo "you are done, the word $key already exist $dNumberOfMatches times";
        } else if ($dNumberOfMatches >= 0) {
            $dRemainingTimes = $value - $dNumberOfMatches;

            $dStep = (int) ($dLength / $dRemainingTimes);

            for ($dIndex = 0; $dIndex < $dRemainingTimes; $dIndex++) {
                $dPosition = $dStep * $dIndex;
                array_splice($aStringContent, $dPosition, 0, $key);
            }


        }
    }
    $sResult = implode(' ', $aStringContent);

    return $sResult;
}

答案 1 :(得分:0)

// create an array of words from the original string
$words = explode(' ', $string);
// a new array to hold the string we are going to create
$newString = array();
// loop all words of the original string
foreach ($words as $i => $w) {
    // add every word to the new string
    $newString[] = $w;
    // loop all keywords
    foreach ($keywords as $kw => $pos) {
        // if the current index ($i) matches the position
        // add the keywords to the new string aswell
        // note that we add 1 to the index first, 
        // since arrays have zero based indexes
        if ($i+1 == $pos) $newString[] = $kw;
    }
}
// create a string from the array of words we just composed
$filled = implode(' ', $newString);