Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7967033
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T06:35:26+00:00 2026-06-04T06:35:26+00:00

I want to replace one random word of which are several in a string.

  • 0

I want to replace one random word of which are several in a string.

So let’s say the string is

$str = 'I like blue, blue is my favorite colour because blue is very nice and blue is pretty';

And let’s say I want to replace the word blue with red but only 2 times at random positions.

So after a function is done the output could be like

I like red, blue is my favorite colour because red is very nice and blue is pretty

Another one could be

I like blue, red is my favorite colour because blue is very nice and red is pretty

So I want to replace the same word multiple times but every time on different positions.

I thought of using preg_match but that doesn’t have an option that the position of the words peing replaced is random also.

Does anybody have a clue how to achieve this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T06:35:27+00:00Added an answer on June 4, 2026 at 6:35 am

    Much as I am loathed to use regex for something which is on the face of it very simple, in order to guarantee exactly n replaces I think it can help here, as it allows use to easily use array_rand(), which does exactly what you want – pick n random items from a list of indeterminate length (IMPROVED).

    <?php
    
        function replace_n_occurences ($str, $search, $replace, $n) {
    
            // Get all occurences of $search and their offsets within the string
            $count = preg_match_all('/\b'.preg_quote($search, '/').'\b/', $str, $matches, PREG_OFFSET_CAPTURE);
    
            // Get string length information so we can account for replacement strings that are of a different length to the search string
            $searchLen = strlen($search);
            $diff = strlen($replace) - $searchLen;
            $offset = 0;
    
            // Loop $n random matches and replace them, if $n < 1 || $n > $count, replace all matches
            $toReplace = ($n < 1 || $n > $count) ? array_keys($matches[0]) : (array) array_rand($matches[0], $n);
            foreach ($toReplace as $match) {
                $str = substr($str, 0, $matches[0][$match][1] + $offset).$replace.substr($str, $matches[0][$match][1] + $searchLen + $offset);
                $offset += $diff;
            }
    
            return $str;
    
        }
    
        $str = 'I like blue, blue is my favorite colour because blue is very nice and blue is pretty';
    
        $search = 'blue';
        $replace = 'red';
        $replaceCount = 2;
    
        echo replace_n_occurences($str, $search, $replace, $replaceCount);
    

    See it working

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to replace the last String which is a , with ) .
I want to replace one string with the other in Perl; both are of
I want to replace the current Java process by a new one just like
I want to replace several different groups of characters in one NSString. Currently I
I want to replace newline \n . If there is one occurrence it gets
I want to replace only the first occurrence of a word in a sentence
I want to replace with the 4~8 characters of a string with * ,how
I want to replace one line of code in 3d party API with my
I want replace default close button in Fancybox 1.3.4 with custom one. I've changed
I want to replace any one of these chars: % \ , [ ]

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.