Home Backend Development PHP Tutorial php顶用正则匹配多个结果,随机替换其中一个结果

php顶用正则匹配多个结果,随机替换其中一个结果

Jun 13, 2016 pm 12:52 PM
index rand replace

php中用正则匹配多个结果,随机替换其中一个结果

用正则匹配字符,如果是全部替换很简单,使用preg_replace就可以了。但是我现在要对得到的多个匹配成功的结果,随机替换其中的一个,这个就有点麻烦了。自己写了个函数解决,不知道有没有其它更好的方法。例子 “I have a dream. I have a dream. I have a dream. I have a dream.”  匹配式 '/i/'。 上面的字符串中有4个匹配结果,我只要随机替换其中的一个。i替换成hell.

我的代码如下:

 

//正则处理函数
function rand_replace_callback($matches) {
    global $g_rand_replace_num, $g_rand_replace_index, $g_rand_replace_str;
    $g_rand_replace_index++;
    if($g_rand_replace_num==$g_rand_replace_index){
        return $g_rand_replace_str;
    }else {
        return $matches[0];
      }        
}

//随机正则替换函数  如果有多个匹配的单元,随机替换其中的一个。 
//注意global $g_rand_replace_num, $g_rand_replace_index, $g_rand_replace_str;这三个全局变量,不要与其它的冲突
//依赖一个正则处理函数 记录匹配单元总数,取一个总数范围内的随机值,在正则处理函数中判断相等则处理。
function rand_preg_replace($pattern, $t_g_rand_replace_str, $string)
{
    global $g_rand_replace_num, $g_rand_replace_index, $g_rand_replace_str;
    preg_match_all($pattern, $string, $out);$find_count = count($out[0]);  //匹配的单元总数
    $g_rand_replace_num = mt_rand(1, $find_count);  //符合正则搜索条件的集合
    $g_rand_replace_index = 0;  //实际替换过程中的index
    $g_rand_replace_str = $t_g_rand_replace_str;
    echo "现在找到符合的有{$find_count}个<br>";
    $ss=preg_replace_callback($pattern,"rand_replace_callback",$string);
    return $ss;
}

$string = "I have a dream. I have a dream. I have a dream. I have a dream.";
echo rand_preg_replace('/I/', "hell", $string);
Copy after login


 


扩展思考,我想减低第一个结果被替换的概念怎么办呢? 有些情况,第一个被替换不是很好,只需要少量的结果是第一个被替换。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What file is index.html? What file is index.html? Feb 19, 2024 pm 01:36 PM

index.html represents the home page file of the web page and is the default page of the website. When a user visits a website, the index.html page is usually loaded first. HTML (HypertextMarkupLanguage) is a markup language used to create web pages, and index.html is also an HTML file. It contains the structure and content of a web page, as well as tags and elements used for formatting and layout. Here is an example index.html code: &lt

How to solve 'undefined: rand.Seed' error in golang? How to solve 'undefined: rand.Seed' error in golang? Jun 25, 2023 am 08:34 AM

During the development or learning process of using Golang, we may encounter the error message of undefined:rand.Seed. This error usually occurs when you need to use a random number generator, because in Golang you need to set a random number seed before you can use the function in the rand package. This article will explain how to resolve this error. 1. Introduce the math/rand package. First, we need to introduce the math/rand package into the code. exist

How to use the REPLACE function to replace a specified part of a string in MySQL How to use the REPLACE function to replace a specified part of a string in MySQL Jul 25, 2023 pm 01:18 PM

MySQL is a commonly used relational database management system that provides a variety of functions to process and operate data. Among them, the REPLACE function is used to replace the specified part of the string. In this article, we will introduce how to use the REPLACE function for string replacement in MySQL and demonstrate its usage through code examples. First, let’s take a look at the syntax of the REPLACE function: REPLACE(str,search_str,replace_str).

What are the string search and replace techniques in Python? What are the string search and replace techniques in Python? Oct 20, 2023 am 11:42 AM

What are the string search and replace techniques in Python? (Specific code example) In Python, strings are a common data type, and we often encounter string search and replace operations in daily programming. This article will introduce some common string search and replacement techniques, accompanied by specific code examples. To find a specific substring in a string, you can use the find() method or index() method of the string. The find() method returns the index of the first occurrence of the substring in the string.

How to synchronize random number generation in Golang parallel processing? How to synchronize random number generation in Golang parallel processing? Jun 03, 2024 pm 02:53 PM

Synchronizing random number generation in Go concurrent programming: Use a mutex (sync.Mutex) to control access to the rand.Rand random number generator. Each goroutine acquires the mutex lock before generating random numbers and releases the mutex lock after generating it. This ensures that only one goroutine can access the random number generator at a time, eliminating data races.

How to solve the problem of generating the same random numbers using php rand function How to solve the problem of generating the same random numbers using php rand function Mar 23, 2023 am 09:17 AM

The rand() function uses the same initial seeds on each call. The default initial seed is obtained from the operating system's time, but it only has microsecond accuracy. That is, within a very short period of time, many rand() function calls will use the same initial seed, resulting in the same random number generation. So, how to solve this problem?

PHP source code running problem: index error solution PHP source code running problem: index error solution Mar 09, 2024 pm 09:24 PM

PHP source code running problem: Index error resolution requires specific code examples. PHP is a widely used server-side scripting language that is often used to develop dynamic websites and web applications. However, sometimes you will encounter various problems when running PHP source code, among which "index error" is a common situation. This article will introduce some common causes and solutions of index errors, and provide specific code examples to help readers better deal with such problems. Problem Description: When running a PHP program

what is mysql index what is mysql index Oct 08, 2023 am 11:47 AM

The index in MySQL means index. It is a data structure used to speed up the query of database tables. The index can be compared to the catalog of a book. It stores the values ​​​​of specific columns in the table and the corresponding row positions, making the database more efficient. Locate and access data quickly. The function of the index is to improve query efficiency. Without an index, the database needs to scan the entire table row by row to find matching data. This method will be very time-consuming in large tables. With an index, the database can The required data rows are quickly located in the order, which greatly improves the query speed.

See all articles