删除逗号和 ' 之后或此符号 ' 前后的空格

remove spaces after comma and ' or before and after this symbol '

我有如下文字,我需要删除逗号和'(单引号)之后或此符号'(单引号)前后的 spaces

$text = "'game', ' open world', ' test rpg'"

预期结果

$text = "'game','open world','test rpg'"

我试过下面这个,但删除了每个 space

$tested = preg_replace('/\s+/', '', $text);

试试这个:

<?php
$text = "'game', ' open world', ' test rpg'";
$str = explode(",",$text);
$arr = array();
foreach ($str as $key) {
    array_push($arr, trim($key));
}

print_r(implode(',',$arr));
?>

查看这些 php 函数 implode and explode

选项 1:

$text  = explode("', ' ",$text);
$text = implode("','",$text);

选项 2:

$text = str_replace("', ' ","','",$text)
echo preg_replace('/\s+?\'\s+?/', '\'', $text);

以下模式应该有效。

Regexr

代码:

$text = "'game', ' open world', ' test rpg'";

echo preg_replace('/(\s?\'\s?)/', "'", $text);

简单快速的解决方案只需使用 php explodeimplode 函数

echo $text = "'game', ' open world', ' test rpg'";
print_r(implode(',',explode(',', $text)));

之前的正则表达式答案不考虑逗号之后的 space(并且不在 ' 之前),例如 open, world。这是一个适用于逗号后跟 space 的解决方案:

$text = "'game', ' open, world', ' test ' rpg'";
echo preg_replace("/(?: *(?='))([',]) */", '', $text);