Table of Contents
PHP使用数组依次替换字符串中匹配项,php数组替换字符串
您可能感兴趣的文章:
Home php教程 php手册 PHP使用数组依次替换字符串中匹配项,php数组替换字符串

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

Jun 13, 2016 am 08:47 AM
mysql php string array

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

先来看个sql语句:

select * from table where ctime >= '[date-14]' and ctime <= '[date-1]';
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 )
Copy after login

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

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

$param = $arr;
array_unshift($param,$sql);
$sql = call_user_func_array('sprintf',$param);
Copy after login

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

说明

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

该函数返回一个字符串或者数组。该字符串或数组是将 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() 基本范例

<&#63;php
// 赋值: <body text='black'>
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");
// 赋值: 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;
&#63;>
Copy after login

Example #2 可能的 str_replace() 替换范例

<&#63;php
// 替换顺序
$str = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order = array("\r\n", "\n", "\r");
$replace = '<br />';
// 首先替换 \r\n 字符,因此它们不会被两次转换
$newstr = str_replace($order, $replace, $str);
// 输出 F ,因为 A 被 B 替换,B 又被 C 替换,以此类推...
// 由于从左到右依次替换,最终 E 被 F 替换
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);
// 输出: apearpearle pear
// 由于上面提到的原因
$letters = array('a', 'p');
$fruit = array('apple', 'pear');
$text = 'a p';
$output = str_replace($letters, $fruit, $text);
echo $output;
&#63;>
Copy after login

注释

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

Caution

了解替换顺序

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

Note:

该函数区分大小写。使用 str_ireplace() 可以进行不区分大小写的替换。

您可能感兴趣的文章:

  • php 将字符串按大写字母分隔成字符串数组
  • 将一维或多维的数组连接成一个字符串的php代码
  • PHP 将逗号、空格、回车分隔的字符串转换为数组的函数
  • PHP 数组和字符串互相转换实现方法
  • 基于php常用函数总结(数组,字符串,时间,文件操作)
  • php的数组与字符串的转换函数整理汇总
  • php中将数组转成字符串并保存到数据库中的函数代码
  • php中利用explode函数分割字符串到数组
  • php二维数组转成字符串示例
  • php判断数组元素中是否存在某个字符串的方法
  • php将字符串随机分割成不同长度数组的方法
  • 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

See all articles