我有一个如下所示的字符串
$string = '["{apple}","{mango}","[apple: red]", "[apple: green]","{pear}" ]';
我想使用preg替换,以便我的结果如下所示
$string = '["{apple}","{mango}","apple:", "apple:","{pear}" ]';
所以只要有方括号,我就需要用最后包含冒号的文本替换它。
答案 0 :(得分:0)
如果 tect 表示类似数组的演示文稿中的键:
$string = '["{apple}","{mango}","[apple: red]", "[apple: green]","{pear}" ]';
$string = preg_replace("/\[(\w+?\:) \w+?\]/","$1" , $string);
// $string now contains "["{apple}","{mango}","apple:", "apple:","{pear}" ]"
答案 1 :(得分:0)
这可以为您提供"[
和第一个:
之间的任何内容。
"\[(.+?):.*?\]"
演示:https://regex101.com/r/lI9yE8/1
PHP用法:
$string = '["{apple}","{mango}","[apple: red]", "[apple: green]","{pear}" ]';
echo preg_replace('/"\[(.+?:).*?\]"/', '"$1"', $string);
输出:
["{apple}","{mango}","apple":, "apple:","{pear}" ]
PHP演示:https://eval.in/498076
在你的例子中,不清楚为什么你的第二个"apple"
没有冒号。如果找到的值不应该冒号移动捕获组外的:
。你的替换字符串有这两种情况,因此不清楚你想要什么。
所以:
(.+?):
或保持原样:
(.+?:)
()
捕获内部的任何内容。