删除逗号和“或此符号前后”的空格

时间:2018-07-10 06:20:11

标签: php regex preg-replace

我有类似波纹管的文字,我需要在逗号和'(单引号)之后或此符号'(单引号)之前和之后删除空格

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

预期结果

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

我已经尝试过这个波纹管,但要删除每个空格

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

6 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

尝试这个:

<?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函数implodeexplode

答案 2 :(得分:0)

选项1:

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

选项2:

$text = str_replace("', ' ","','",$text)

答案 3 :(得分:0)

以下模式应该有效。

Regexr

代码:

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

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

答案 4 :(得分:0)

简单快速的解决方案,只需使用php <%@page import="java.io.FileOutputStream"%> <%@page import="net.sf.jasperreports.engine.JRExporterParameter"%> <%@page import="net.sf.jasperreports.engine.JRExporter"%> <%@page import="java.io.ByteArrayOutputStream"%> <%@page import="com.sun.xml.internal.ws.message.ByteArrayAttachment"%> <%@page import="net.sf.jasperreports.engine.export.JRPdfExporter"%> <%@page import="net.sf.jasperreports.engine.JasperExportManager"%> <%@page import="java.util.HashMap"%> <%@page import="net.sf.jasperreports.engine.JasperFillManager"%> <%@page import="net.sf.jasperreports.engine.JasperReport"%> <%@page import="net.sf.jasperreports.engine.JasperPrint"%> <%@page import="java.sql.ResultSet"%> <%@page import="java.sql.Statement"%> <%@page import="java.sql.DriverManager"%> <%@page import="java.sql.Connection"%> <%@page contentType="application/pdf"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Pagess</title> </head> <body> <% Class.forName("com.mysql.jdbc.Driver"); %> <% Connection con = DriverManager.getConnection("jdbc:mysql://localhost/db_penjualan", "root", ""); %> <% HashMap map = new HashMap(); map.put("KodeKonsumen", "k001"); JasperPrint print = JasperFillManager.fillReport(application.getRealPath("LaporanDataKonsumen.jasper"), map, con); JasperExportManager.exportReportToPdfStream(print, response.getOutputStream()); %> </body> </html> explode函数

implode

答案 5 :(得分:0)

以前的正则表达式答案不考虑逗号之后(而不是id=之前)的空格,例如'。这是一个适用于逗号和空格的解决方案:

open, world