Home > Backend Development > PHP Tutorial > 求段代码:判断数组里是否有重复内容,如果有就只更新指定数量,没有就添加

求段代码:判断数组里是否有重复内容,如果有就只更新指定数量,没有就添加

WBOY
Release: 2016-06-23 13:54:11
Original
982 people have browsed it

内容:

一年级 X 2, 二年级 X 10 ,三年级 X 5 ……

判断里面是否有二年级,如果有就加5 结果:一年级 X 2, 二年级 X 15 ,三年级 X 5 ……


回复讨论(解决方案)

$ar = array(  '一年级 X 2',  '二年级 X 10',  '三年级 X 5',);if($t = preg_grep('/^二年级/', $ar)) {  $ar[key($t)] = preg_replace('/\d+$/e', '$0 + 5', current($t));}print_r($ar);
Copy after login
Array(    [0] => 一年级 X 2    [1] => 二年级 X 15    [2] => 三年级 X 5)
Copy after login

如果不是数组,那怎么操作:
比如:
$qq="一年级 X 2, 二年级 X 10 ,三年级 X 5 ";

$qq = "一年级 X 2, 二年级 X 10 ,三年级 X 5 ";$k = '二年级';echo preg_replace("/(?<=$k X )\d+/e", '$0 + 5', $qq);
Copy after login
一年级 X 2, 二年级 X 15 ,三年级 X 5 

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template