从字符串中删除 2 个字符之间的反斜杠
Remove Backslash between 2 characters from string
我只需要替换 2 个字符之间的反斜杠,引号 (") 除外
如果我有这个字符串:
When I look at you, I\understand why I live //replace
When I look at you, I "\understand why I live // No replace
When I look at you, I"\understand why I live // No replace
Sword art online\Мастера меча онлайн opening //replace Sword art online Мастера меча онлайн opening
这是针对 json 字符串的,但如果我使用 stripslashes,所有反斜线都将被删除。如果字符串没有 " 引号,我只需要删除。
非常感谢。
你可以使用这个:
$text = preg_replace('~"[^"]*"\K|\\~', '', $text);
或这个:
$text = preg_replace('~"[^"]*"(*SKIP)(*F)|\\~', '', $text);
这两个模式使用引号括起来的字符。
第一个模式使用 \K
从匹配结果中删除左侧匹配的所有字符。第二个强制模式失败((*F)
)并且不重试引号之间的字符((*SKIP)
)。
请注意,在模式字符串中必须写入文字反斜杠 \\
。 (反斜杠为字符串转义一次,为正则表达式引擎转义一次)。
试试这个:
$strings = array(
'When I look at you, I\understand why I live',
'When I look at you, I "\understand why I live',
'When I look at you, I"\understand why I live',
'Sword art online\Мастера меча онлайн opening'
);
foreach ($strings as $string) {
$str = addslashes(stripslashes($string));
var_dump($str);
}
我只需要替换 2 个字符之间的反斜杠,引号 (") 除外
如果我有这个字符串:
When I look at you, I\understand why I live //replace
When I look at you, I "\understand why I live // No replace
When I look at you, I"\understand why I live // No replace
Sword art online\Мастера меча онлайн opening //replace Sword art online Мастера меча онлайн opening
这是针对 json 字符串的,但如果我使用 stripslashes,所有反斜线都将被删除。如果字符串没有 " 引号,我只需要删除。
非常感谢。
你可以使用这个:
$text = preg_replace('~"[^"]*"\K|\\~', '', $text);
或这个:
$text = preg_replace('~"[^"]*"(*SKIP)(*F)|\\~', '', $text);
这两个模式使用引号括起来的字符。
第一个模式使用 \K
从匹配结果中删除左侧匹配的所有字符。第二个强制模式失败((*F)
)并且不重试引号之间的字符((*SKIP)
)。
请注意,在模式字符串中必须写入文字反斜杠 \\
。 (反斜杠为字符串转义一次,为正则表达式引擎转义一次)。
试试这个:
$strings = array(
'When I look at you, I\understand why I live',
'When I look at you, I "\understand why I live',
'When I look at you, I"\understand why I live',
'Sword art online\Мастера меча онлайн opening'
);
foreach ($strings as $string) {
$str = addslashes(stripslashes($string));
var_dump($str);
}