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 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据