drgaeqdqiiyg14608 2018-05-13 18:38
浏览 50
已采纳

php - > preg_replace - >仅在引号之间删除空格

I'm trying to remove space ONLY between quotes like:

$text = 'good with spaces "here all spaces should be removed" and here also good';

can someone help with a working piece of code ? I already tried:

$regex = '/(\".+?\")|\s/';

or

$regex = '/"(?!.?\s+.?)/';

without success, and I found a sample that works in the wrong direction :-( Removing whitespace-characters, except inside quotation marks in PHP? but I can't change it.

thx Newi

  • 写回答

2条回答 默认 最新

  • dpdt79577 2018-05-13 18:59
    关注

    This kind of problem are easily solved with preg_replace_callback. The idea consists to extract the substring between quotes and then to edit it in the callback function:

    $text = preg_replace_callback('~"[^"]*"~', function ($m) {
        return preg_replace('~\s~', '#', $m[0]);
    }, $text);
    

    It's the most simple way.


    It's more complicated to do it with a single pattern with preg_replace but it's possible:

    $text = preg_replace('~(?:\G(?!\A)|")[^"\s]*\K(?:\s|"(*SKIP)(*F))~', '#', $text);
    

    demo

    Pattern details:

    (?:
        \G (?!\A)  # match the next position after the last successful match
      |
        "          # or the opening double quote
    )
    [^"\s]*        # characters that aren't double quotes or a whitespaces
    \K             # discard all characters matched before from the match result
    (?:
        \s         # a whitespace
      |
        "           # or the closing quote
        (*SKIP)(*F) # force the pattern to fail and to skip the quote position
                    # (this way, the closing quote isn't seen as an opening quote
                    # in the second branch.)
    )
    

    This way uses the \G anchors to ensure that all matched whitespaces are between the quotes.

    Edge cases:

    • there's an orphan opening quote: In this case, all whitespaces from the last quote until the end of the string are replaced. But if you want you can change this behavior adding a lookahead to check if the closing quote exists:

      ~(?:\G(?!\A)|"(?=[^"]*"))[^"\s]*\K(?:\s|"(*SKIP)(*F))~

    • double quotes can contain escaped double quotes that have to be ignored: You have to describe escaped characters like this:

      ~(?:\G(?!\A)|")[^"\s\\\\]*+(?:\\\\\S[^"\s\\\\]*)*+(?:\\\\?\K\s|"(*SKIP)(*F))~


    Other strategy suggested by @revo: check if the number of remaining quotes at a position is odd or even using a lookahead:

    \s(?=[^"]*+(?:"[^"]*"[^"]*)*+")
    

    It is a short pattern, but it can be problematic with long strings since for each position with a whitespace you have to check the string until the last quote with the lookahead.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请提供一个符合要求的网页链接。
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码