删除空格字符,除了PHP中的引号之外? [英] Removing whitespace-characters, except inside quotation marks in PHP?

查看:95
本文介绍了删除空格字符,除了PHP中的引号之外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从字符串中删除所有空格,但是引号应保持原样.

I need to remove all whitespace from string, but quotations should stay as they were.

这是一个例子:

string to parse:
hola hola "pepsi cola" yay

output:
holahola"pepsi cola"yay

有什么主意吗?我确定可以使用正则表达式来完成此操作,但是任何解决方案都可以.

Any idea? I'm sure this can be done with regex, but any solution is okay.

推荐答案

我们可以将字符串或引号与

We could match strings or quotations with

[^\s"]+|"[^"]*"

所以我们只需要preg_match_all并连接结果即可.

So we just need to preg_match_all and concatenate the result.

示例:

$str = 'hola hola "pepsi cola" yay';

preg_match_all('/[^\s"]+|"[^"]*"/', $str, $matches);

echo implode('', $matches[0]);
// holahola"pepsi cola"yay

这篇关于删除空格字符,除了PHP中的引号之外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆