从字符串中删除特殊字符“ |”,如果在开始|“结束” |之间包含“,”,则忽略它

时间:2020-06-30 22:17:48

标签: php regex preg-replace

字符串:

(STR,0:30)+ |“室外” | + |“椅子垫”,“商业地板垫”,“门垫” | + [帖子类型] +(STR,0:30)

结果:

(STR,0:30)+“室外” + |“椅子垫”,“商业地板垫”,“门垫” | + [帖子类型] +(STR,0:30)

我尝试过

preg_replace('/\|\"[a-z A-Z]\"\|/i', '"', $string);

我无法找到任何解决方案,我所知道的唯一条件是该字符串将以|"开头并以"|结尾,并且如果该字符串不包含","删除|""|"

2 个答案:

答案 0 :(得分:0)

我认为您可以使用这样的正则表达式:

\|("[^,]+")\|

Regex demo

$re = '/\|("[^,]+")\|/m';
$str = '(STR,0:30) + |"Outdoor"| + |"Chair Mat","Commercial Floor Mat","Door Mat"| + [Post Type] + (STR,0:30)';
$subst = '$1';

$result = preg_replace($re, $subst, $str);

echo "The result of the substitution is ".$result;
// (STR,0:30) + "Outdoor" + |"Chair Mat","Commercial Floor Mat","Door Mat"| + [Post Type] + (STR,0:30)

答案 1 :(得分:0)

尽管未在问题中明确说明,但此任务的目的是询问管道封闭的子字符串。 如果子字符串中包含多个双引号子字符串,则必须保留管道。如果管道内只有一个双引号子串,则应删除这些管道。该问题涉及检查逗号,但是如果其中一个双引号子串包含一个逗号,则会导致错误的结果。逗号。如果在双引号子串中存在一个转义的双引号,则可能会发生相同类型的混乱情况。

不了解我要怎么做?我能理解,所以我有一个演示和一个新的正则表达式模式,该模式借鉴了the wisdom of this post

代码:(Demo

$strings = [
    '(STR,0:30) + |"Outdoor"| + |"Chair Mat","Commercial Floor Mat","Door Mat"| + [Post Type] + (STR,0:30)',
    '(STR,0:30) + |"Outdoor"| + |"Red, Yellow, and Green Jamaican Mat"| + [Post Type] + (STR,0:30)',
    '(STR,0:30) + |"Outdoor"| + |"USA \"MAGA\" Mat"| + [Post Type] + (STR,0:30)',
];

print_r(
    preg_replace('~\|("[^"\\\\]*(?:\\\\"[^"\\\\]*)*")\|~', '\1', $strings)
);

输出:

Array
(
    [0] => (STR,0:30) + "Outdoor" + |"Chair Mat","Commercial Floor Mat","Door Mat"| + [Post Type] + (STR,0:30)
    [1] => (STR,0:30) + "Outdoor" + "Red, Yellow, and Green Jamaican Mat" + [Post Type] + (STR,0:30)
    [2] => (STR,0:30) + "Outdoor" + "USA \"MAGA\" Mat" + [Post Type] + (STR,0:30)
)

请注意如何将"Chair Mat","Commercial Floor Mat","Door Mat"正确地视为多个条目。相反,"Red, Yellow, and Green Jamaican Mat""USA \"MAGA\" Mat"是单个条目,因此适当地删除了它们的管道。