Home Backend Development PHP Tutorial PHP怎么依次替换字符串中匹配项

PHP怎么依次替换字符串中匹配项

May 28, 2016 am 11:49 AM

PHP怎么依次替换字符串中匹配项

PHP怎么替换字符串中匹配项?

PHP使用数组依次替换字符串中匹配项

先来看个sql语句:

select * from table where ctime >= &#39;[date-14]&#39; and ctime <= &#39;[date-1]&#39;;
Copy after login

想把上面这句sql的中括号表示的日期依次换成下面的数组中的元素array('2015-07-01','2015-07-15');

用正则匹配:找到第一个中括号部分,用第一个元素替换,然后找第二个,再替换

用sprintf函数:因为日期已经计算好,按照顺序替换就可以了.

因为markdown写正则比较麻烦,这里就直接上图片了

ps:设想一下,如sql中只有一个需要替换的时间条件,就需要修改成

$sql = sprintf($sql,$arr[0])
Copy after login

说白了呢就是如果sprintf函数支持第二个参数是数组就太好了。查了一番之后确实可以有解决办法:

call_user_func_array() 官方的解释是:

call_user_func_array — 调用回调函数,并把一个数组参数作为回调函数的参数

mixed call_user_func_array ( callable $callback , array $param_arr )

把第一个参数作为回调函数(callback)调用,把参数数组作(param_arr)为回调函数的的参数传入。

也就是说:第一个参数是你想要使用的函数名(上文中的sprintf),第二个参数是将要使用函数的参数,只不过参数是以数组形式传给了call_user_func_arrayok,这样的话就可以实现动态的替换了

$param = $arr;
array_unshift($param,$sql);
$sql = call_user_func_array(&#39;sprintf&#39;,$param);
Copy after login

接下来介绍str_replace — 子字符串替换,数组替换

说明

mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

该函数返回一个字符串或者数组。该字符串或数组是将 subject 中全部的 search 都被 replace 替换之后的结果。

如果有一些特殊的替换需求(比如正则表达式),你应该使用该函数替换 ereg_replace() 和 preg_replace()。

参数

如果 search 和 replace 为数组,那么 str_replace() 将对 subject 做二者的映射替换。如果 replace 的值的个数少于 search 的个数,多余的替换将使用空字符串来进行。如果 search 是一个数组而 replace 是一个字符串,那么 search 中每个元素的替换将始终使用这个字符串。该转换不会改变大小写。

如果 search 和 replace 都是数组,它们的值将会被依次处理。

search

查找的目标值,也就是 needle。一个数组可以指定多个目标。

replace

search 的替换值。一个数组可以被用来指定多重替换。

subject

执行替换的数组或者字符串。也就是 haystack。

如果 subject 是一个数组,替换操作将遍历整个 subject,返回值也将是一个数组。

count

Note: 如果被指定,它将控制匹配和替换的次数。

返回值

该函数返回替换后的数组或者字符串。

版本 说明

5.0.0 新增 count 参数。

4.3.3 函数行为改变。旧的版本中存在一个 BUG —— 当 search 和 replace 两个参数都是数组的时候,将导致空的 search 索引被跳过,但是却没有同时前移 replace 内部指针。该错误发生在 PHP

4.3.3,任何依赖于此 BUG 的脚本应该先除去空的查找值,从而模拟原始的行为。

4.0.5 大多数参数都可以为数组。

范例

Example #1 str_replace() 基本范例

<?php
// 赋值: 
$bodytag = str_replace("%body%", "black", "");
// 赋值: Hll Wrld f PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
// 赋值: You should eat pizza, beer, and ice cream every day
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy = array("pizza", "beer", "ice cream");
$newphrase = str_replace($healthy, $yummy, $phrase);
// 赋值: 2
$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count;
?>
Example #2 可能的 str_replace() 替换范例
<?php
// 替换顺序
$str = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order = array("\r\n", "\n", "\r");
$replace = &#39;
&#39;;
// 首先替换 \r\n 字符,因此它们不会被两次转换
$newstr = str_replace($order, $replace, $str);
// 输出 F ,因为 A 被 B 替换,B 又被 C 替换,以此类推...
// 由于从左到右依次替换,最终 E 被 F 替换
$search = array(&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;);
$replace = array(&#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;);
$subject = &#39;A&#39;;
echo str_replace($search, $replace, $subject);
// 输出: apearpearle pear
// 由于上面提到的原因
$letters = array(&#39;a&#39;, &#39;p&#39;);
$fruit = array(&#39;apple&#39;, &#39;pear&#39;);
$text = &#39;a p&#39;;
$output = str_replace($letters, $fruit, $text);
echo $output;
?>
Copy after login

注释

Note: 此函数可安全用于二进制对象。

Caution

了解替换顺序

由于 str_replace() 的替换时从左到右依次进行的,进行多重替换的时候可能会替换掉之前插入的值。参见该文档的范例。

更多相关知识,请访问PHP中文网

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks 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)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles