0

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

$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";

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

4

2 回答 2

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;
}
于 2013-09-07T10:42:42.063 回答
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);
于 2013-09-07T10:40:36.420 回答