ai didi

php - preg_replace 在省略时插入默认值

转载 作者:可可西里 更新时间:2023-10-31 22:12:34 24 4
gpt4 key购买 nike

我正在尝试为 preg_replace 处理一些正则表达式,当它不在主题中时,它会插入一个默认的 key="value"。

这是我所拥有的:

$pattern = '/\[section([^\]]+)(?!type)\]/i';
$replacement = '[section$1 type="wrapper"]';

我想让它变成:

[section title="This is the title"]

进入:

[section title="This is the title" type="wrapper"]

但是当有值的时候,我不希望它匹配。这意味着:

[section title="This is the title" type="full"]

会保持不变。

我错误地使用了负前瞻。第一部分将始终匹配, (?!type) 变得无关紧要。我不确定如何放置它才能正常工作。有什么想法吗?

最佳答案

应该是

/\[(?![^\]]*type)section([^\]]*)\]/i
------------- ------
| |->your required data in group 1
|->match further only if there is no type!

尝试一下 here

关于php - preg_replace 在省略时插入默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16860340/

24 4 0
文章推荐: php - 如何为 CSV、fgetcsv() 问题转义逗号
文章推荐: php - 网页请求中止
文章推荐: javascript - 从本地网络访问 Gulpjs Web 服务器
文章推荐: php - Twitter oAuth - 请求 token
可可西里
个人简介

我是一名优秀的程序员,十分优秀!

滴滴打车优惠券免费领取
滴滴打车优惠券
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com