dregvw1801 2013-09-07 09:38
浏览 71
已采纳

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

I have a string and key words array like this.

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

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

So I need to put these keywords into the string with number of times according to the key words array as following. And without repeating these key words.

$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

Without repeating like this.

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

Anyone can help me? Really appreciate it. Thanks

  • 写回答

2条回答 默认 最新

  • duanjue9889 2013-09-07 10:42
    关注
        $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条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?