【问题标题】:get substring in php with preg_match使用 preg_match 在 php 中获取子字符串
【发布时间】:2016-01-06 13:26:59
【问题描述】:

我有一个类似下面的字符串

$string = '["{apple}","{mango}","[apple: red]", "[apple: green]","{pear}" ]';

我想使用 preg 替换,这样我的结果如下所示

$string = '["{apple}","{mango}","apple:", "apple:","{pear}" ]';

因此,只要有方括号,我就需要将其替换为末尾包含冒号的文本。

【问题讨论】:

  • 一个有错字的“文本”

标签: php regex preg-replace str-replace


【解决方案1】:

这应该为您提供介于 "[ 和第一个 : 之间的任何内容。

"\[(.+?):.*?\]"

演示: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" 没有冒号。如果找到的值不应该有冒号,则将: 移到捕获组之外。您的替换字符串有两种情况,所以不清楚您想要什么。

所以:

(.+?):

或保持原样:

(.+?:)

() 捕获内部的任何内容。

【讨论】:

  • 工作完美,但我需要苹果的双引号。输出应该是 ["{apple}","{mango}","apple:", "apple:","{pear}" ]
  • 编辑了丢失的问题:在第二个苹果之后
  • 替换字符串只需更新为'"$1"'
【解决方案2】:

如果 tect 表示类似数组的表示中的键:

$string = '["{apple}","{mango}","[apple: red]", "[apple: green]","{pear}" ]';

$string = preg_replace("/\[(\w+?\:) \w+?\]/","$1" , $string);

// $string now contains  "["{apple}","{mango}","apple:", "apple:","{pear}" ]"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 2011-08-21
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    相关资源
    最近更新 更多