PHP使用数组依次替换字符串中匹配项,php数组替换字符串
PHP使用数组依次替换字符串中匹配项,php数组替换字符串
先来看个sql语句:
select * from table where ctime >= '[date-14]' and ctime <= '[date-1]';
想把上面这句sql的中括号表示的日期依次换成下面的数组中的元素array('2015-07-01','2015-07-15');
用正则匹配:找到第一个中括号部分,用第一个元素替换,然后找第二个,再替换
用sprintf函数:因为日期已经计算好,按照顺序替换就可以了.
因为markdown写正则比较麻烦,这里就直接上图片了
ps:设想一下,如sql中只有一个需要替换的时间条件,就需要修改成
$sql = sprintf($sql,$arr[0])
说白了呢就是如果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('sprintf',$param);
接下来介绍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 // 赋值: <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; ?>
Example #2 可能的 str_replace() 替换范例
<?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; ?>
注释
Note: 此函数可安全用于二进制对象。
Caution
了解替换顺序
由于 str_replace() 的替换时从左到右依次进行的,进行多重替换的时候可能会替换掉之前插入的值。参见该文档的范例。
Note:
该函数区分大小写。使用 str_ireplace() 可以进行不区分大小写的替换。
您可能感兴趣的文章:
- php 将字符串按大写字母分隔成字符串数组
- 将一维或多维的数组连接成一个字符串的php代码
- PHP 将逗号、空格、回车分隔的字符串转换为数组的函数
- PHP 数组和字符串互相转换实现方法
- 基于php常用函数总结(数组,字符串,时间,文件操作)
- php的数组与字符串的转换函数整理汇总
- php中将数组转成字符串并保存到数据库中的函数代码
- php中利用explode函数分割字符串到数组
- php二维数组转成字符串示例
- php判断数组元素中是否存在某个字符串的方法
- php将字符串随机分割成不同长度数组的方法
- PHP实现多维数组转字符串和多维数组转一维数组的方法

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

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.

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen
